Gio
Gio

Reputation: 165

Animation only works once

There is a small problem with my javascript code. The animate fucntion only works once when I click on .add-case. Still the alert within the 'on' function show 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
}); 

Anyone that could help?

Upvotes: 3

Views: 534

Answers (3)

Gio
Gio

Reputation: 165

The problem was indeed the use of (this). Changed it to $('.filling') and it works.

Upvotes: 1

Himesh
Himesh

Reputation: 36

Instead of using "this", try getting the object by its id or class. As shown here:

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

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

If you are using this, it may be giving document object.

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Problem:

The problem here is the height of the clicked element is not changed on click. So, on every click the same height is retrieved and updated.

$(this).height()

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

Solution:

Use relative size +=40 to increase the height by 40. Although, $(elementSelector).height() + 40 can also be used, but it's better to use relative units.

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

$(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>

Upvotes: 2

Related Questions