简体   繁体   中英

jQuery toggle and slidetoggle on click event toggles the element with weird bounce after toggle

I am new to jQuery and JavaScript. I have list of elements which I set to display: none Upon click on the certain element, the list of elements should toggle down. It toggles down but the problem is after toggling down it bounces.

<div class="category">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
     <h1 class="categoryHeading">Transportation</h1>
    <div class="items">
      <p class="item">MVV</p>
      <p class="item">Bike</p>
    </div>
  </div>

I read on the stackoverflow that it might be because of click event bubbles up the DOM and gets triggered multiple times. So I have tried by adding the line e.stopPropagation(); but no success.

$(".categoryHeading").click(function(e){
            e.stopPropagation();

      $(".items").toggle(1000);

After I set the margin for the ".items" the bounces have gotten disappeared. Can anyone explain me why there is a weird behaviour?
});

JSBIN link

The toggle event puts a few lines of style into the <div class="items"> . Namely, the following:

display: block;
overflow: hidden;
height: 75.9189px; // this value goes up/down
padding: 0px;
margin: 0px;
width: 330.892px;
opacity: 0.89527; // this value goes up/down

After the animation, only one property is still available: display: block;

If you add overflow: hidden , the bump is gone. So, add overflow: hidden to .items {} .


The problem, however, is caused by the padding , which is part of the <p> element. If the property overflow:hidden; is set on the parent, the margin around the child ( <p> ) is not used (because the overflow of the parent is hidden). This is the reason, it jumps up.


Here is how I found out, what properties are set to the element during the JavaScript animation (asked for in the comments):

The animation is made with JavaScript. Because it is quite easy to increase the duration of the animation, I've changed this value to 5000. Then, in the Developer Tools (of Chrome) you can go to the Sources tab and stop the execution of JavaScript (Pause icon on the right or just F8 with the focus on the DevTools). Afterwards, you can go to the elements tab and see the elements with their styles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM