Kevin
Kevin

Reputation: 15

Jquery help: .click() to each individual element

I've written up this code to add a class (.box-open which adds display:block) to my box (.sharebox) when a button (#share-but) is clicked but the problem is I'm having trouble making this only apply to one .share div at a time because everytime I click a button, all the .shareboxs get the class .box-open applied to it.

function shareBox() {
$('.share').each(function( index ) {
    $(this).on('click', '#share-but', function() {
        if ($('.sharebox').hasClass('box-open')) {
            $('.sharebox').removeClass('box-open');
        }        
        else {
            $('.sharebox').addClass('box-open');
        }
    });
});
}
shareBox();

Here is an image of the problem (I'm building a Tumblr Theme). Hopefully it's a lot easier to understand. http://24.media.tumblr.com/c5c4252607bf4a9905c7c9de5b592c60/tumblr_ml4t2fSuQo1rqce8co1_500.png <---- This happened when I clicked one of the buttons, but I only want one .sharebox to have the class .box-open added to it when I click the #share-but inside the same .share div.

I hope all of this made sense. I'm still very noob at Javascript/Jquery as I only started learning like 2 weeks ago so any help is much appreciated!

Upvotes: 1

Views: 659

Answers (2)

Adil
Adil

Reputation: 148110

You have to use $(this) instead of $('.sharebox') to address source of event

$('.sharebox').addClass('box-open');

Would be

$(this).addClass('box-open');

The id of element is supposed to be unique in document so you can bind click directly to '#share-but', if it is not unique you can bind it like this.

$('.share').on('click', '#share-but', function() {
    if ($('.sharebox').hasClass('box-open')) {
        $('.sharebox').removeClass('box-open');
    }        
    else {
        $('.sharebox').addClass('box-open');
    }
});

You can use toggleClass to make it simple, I assume you have single item with id #share-but,

$('#share-but').click(function(){
   $(this).toggleClass("box-open");
});

Upvotes: 1

Jaco Koster
Jaco Koster

Reputation: 497

This would be a simpler version, you can toggle the classname :)

   $('.share').on("click", "#share-but", function() {
      $(this).find(".sharebox").toggleClass('box-open');
  });

Upvotes: 0

Related Questions