Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  60] [ 3]  / answers: 1 / hits: 19440  / 10 Years ago, mon, september 15, 2014, 12:00:00

I'm developing an application where I need to add class active for both hover and click events.

The challenge I am facing here is when I hover my content, it adds the class active. There is no problem in that.

Since it is active now, when I am about to click on content it should hold up with the class active. But instead it goes to the normal state and it toggles the class.



JQuery



$(div).hover(
function() {
$(this).addClass('active');
}, function() {
$( this ).removeClass('active');
}
);
$( div ).click(function(){
$(this).toggleClass('active');
});


DEMO


More From » jquery

 Answers
7

Use CSS for the hover event



div:hover{background:red;}


And remove the hover event from your Javascript:



$( div ).click(function(){
$(this).toggleClass('active');
});


Fiddle



If you want the same functionality without CSS.



Add a second class called clicked. Let the hover event check for this class before removing the class.



$(div).hover(
function() {
$(this).addClass('active');
}, function() {
if(!$( this).hasClass('clicked') ){
$( this ).removeClass('active');
}
}
);

$(div).click(function(){
$(this).toggleClass('clicked');
});


Fiddle


[#69452] Friday, September 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;