Question

Code:

    <script>
$(document).ready(function() {

  $('.boxes').on('click', function(e){
    e.preventDefault();
    var $btn = $(this);
    $btn.toggleClass('opened');

    var heights = $btn.hasClass('opened') ? 300 : 100 ;
    $('.boxes').stop().animate({height: heights });
  });
});
    </script>

I have 18 boxes that have the class boxes. As you can imagine by clicking .boxes all 18 boxes open and close. What I want to do is make sure that only the box that is clicked opens and closes rather than all of them. The 18 boxes have unique ids like box1, box2, box3, etc.

I am new to JS so to me a logical solution would be repeating the above code 18 times and use the id's unique to the boxes but I know that that's too much code repetition. So, how can I make sure that only the box that is clicked is the one that opens and closes rather than all of them? Any tip will be helpful. Thanks!

Was it helpful?

Solution

EDIT: Give it a try now.

$(".boxes").on('click', function(e) {
    e.preventDefault();
    $(this).toggleClass('opened');
    var heights = $(this).hasClass('opened') ? 300 : 100 ;

    $(this).stop().animate({height: heights}); //Show clicked box
});

JSFiddle

OTHER TIPS

Can't you just change $('.boxes') to $btn? That will animate only the box that is clicked.

$btn.stop().animate({height: heights });
^^^^

changing $('.boxes').stop().animate({height: heights }); to

$(this).stop().animate({height: heights });

will toggle only selected box. Check out fiddle http://jsfiddle.net/xSNYc/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top