Animation only works once.

There is a little problem with my javascript code. The fucntion animation only works once when I click on .add-case. However, a warning in the 'on' function is displayed every time.

$(document).on('click', '.add-case', function(){
    height = $('.filling').height(); 
    alert('Works') // This shows every time I click
    $('.filling').animate({ height: $(this).height() + 40}, 600); 
    // this only works once
}); 

Who could help?

+4
source share
3 answers

Problem:

The problem is that the element heightof the clicked element does not change when clicked. Thus, on each click, the same height is restored and updated.

$(this).height()

will get the height of the clicked item . $(this)inside the event handler is the jQuery object of the element on which the event occurred.

Decision:

+=40, 40. , $(elementSelector).height() + 40 , .

. + = - = , .

$(document).on('click', '.add-case', function() {
  $('.filling').animate({
    height: '+=40'
  }, 600);
});
.filling {
  height: 10px;
  width: 50%;
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="filling"></div>

<button class="add-case">Click</button>
Hide result
+2

, (). $('.filling'), .

+2

"this" . :

https://jsfiddle.net/HimeshS/y1cqsovg/

 $('.filling').animate({ height: $(".filling").height() + 40}, 600);

, .

+1

Source: https://habr.com/ru/post/1613176/


All Articles