简体   繁体   中英

How to know which element is clicked and toggle class to it? JS Jquery

I have 4 divs like this, with class work :

<div class="work">
    <img src="panda.jpg">
    <h3>Panda</h3>
    <p>Panda eats apple.</p>
</div>

And I want to toggle clicked class to clicked div :

.clicked {
 font-size: 25px;
}

How to do it?

There is a function in jquery named toggleClass .

You should attach a click event to your div and then use this to reference to the clicked element.

$('.work').click(function() {    // edited: from $(.work) to $('.work')
    $(this).toggleClass("click")
})
$('.work').on('click', function() {
    $(this).toggleClass('clicked');
})

Geez, why couldn't you just go check the documentation!

Jquery has a method just for that.

$('.work').click(function(e) {
    $(e.target).closest('.work').toggleClass('clicked');
});

The .closest() is in case the click was registered on the contained image, etc.

If you want only one of the div's with the class .work to have the .clicked class at a time, here's what you do:

$('.work').on('click', function() {    //When the div 'work' is clicked

   $('.work').removeClass('clicked'); //Remove the class 'clicked' from all divs named 'work'

   $(this).addClass('clicked');     //Add the class 'clicked' to the div that was clicked.

});

Here's a fiddle for the same.

Here you go with a solution https://jsfiddle.net/7ep3e4gn/

 $('div.work').click(function(){ $(this).addClass('clicked').siblings('div.work').removeClass('clicked'); }); 
 .clicked { font-size: 25px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="work"> <img src="panda.jpg"> <h3>Panda</h3> <p>Panda eats apple.</p> </div> <div class="work"> <img src="panda.jpg"> <h3>Panda2</h3> <p>Panda2 eats apple.</p> </div> <div class="work"> <img src="panda.jpg"> <h3>Panda3</h3> <p>Panda3 eats apple.</p> </div> 

I've used addClass & removeClass along with jQuery siblings method.

Hope this will help you.

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