Tutorial :Jquery how to unclick() element?



Question:

I have a table which has lots of <td></td>. what i want to do is add CSS to the <td> when it got clicked, and remove the CSS from that <td> when user click other <td>, how can i implement that? Thanks.


Solution:1

var lastTD;  $('td').click(function(){      if (lastTD) lastTD.removeClass('some-class');      lastTD = $(this).addClass('some-class');  });  

CSS:

.some-class { color: red; ... }  


Solution:2

// For click on an element  $('#element_id').click(function() {//or class or any selector   //change css class   });  // For outside of an element  $('body').click(function() {   //change css class   });  


Solution:3

Something like:

$('td').removeClass('active')  $(this).addClass('active')  

i.e. you remove the active class from all td; then add that class to a specific one.


Solution:4

You can do something like event delegation to capture clicks on the entire table and remove the class.

$('#my-table').click(function(event) {      $(this).find('td').removeClass('clicked');      var target = $(event.target);      if (target.is('td')) {          target.addClass('clicked');          event.stopPropagation();      }  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »