Wednesday 24 February 2016

javascript - Best way to dynamically add and remove style on elements



I am using mouseenter and mouseleave events on some elements to change their appearance. I am able to do so using either of the following two strategies:




  1. $(this).css('someProperty','someValue') to add and then $(this).removeAttr('style') to remove

  2. $(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove



What is the best way to do so?


Answer



Definitely option 2. Styles should be defined in the stylesheet.



There's also toggleClass, which removes the class if it's there, but adds it if it's missing.






Note: toggleClass also lets you pass in a Boolean as the second argument, telling it whether to add or remove it (regardless of whether it currently has that class applied), so:



$(this).toggleClass('active', true);


is exactly equivalent to:



$(this).addClass('active');


This is very handy when you have a Boolean in your code already. So instead of this:



if (isUserActive()) {
$(this).addClass('active');
} else {
$(this).addClass('active');
}


You could just do this:



$(this).toggleClass('active', isUserActive());

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...