Reputation: 29
I'm trying to toggle some css whilst I hover over a div. Normally I would use 'toggleclass' but the new background color doesn't seem to overwrite the existing class so I resorted to the method below.
The issue is how to toggle the css off after the hover.
$('#menu_first_home').hover(function(){
$(this).css({ 'border': '10px solid rgba(186, 0, 0, 0.2)' });
$('.search-box').css({ 'background-color': 'rgba(186, 0, 0, 0.5)', 'color': 'rgba(186, 0, 0, 0.5)' });
});
Upvotes: 0
Views: 265
Reputation: 4490
You can use jquery hover method along with css classes to solve it. hover method accept two callback function, one when the pointer moves over the item, and one when it leaves:
$(item).hover(function() { ... }, function() { ... });
Instead of adding styles dynamically, define it in css files :
#menu_first_home.hoverClass {
border-color: rgba(186, 0, 0, 0.2);
}
and on hover, add the class (e.g. "hoverClass") to that particular element, and on mouse out remove it.
Here is the live working demo.
Upvotes: 0
Reputation: 6933
ToggleClass should work, but here is an example for your code to change the css attributes on mouseleave
$('#menu_first_home').hover(
function () { // Mouseenter
$(this).css({
'border': '10px solid rgba(186, 0, 0, 0.2)'
});
$('.search-box').css({
'background-color': 'rgba(186, 0, 0, 0.5)',
'color': 'rgba(186, 0, 0, 0.5)'
});
}, function(){ // Mouseleave
$(this).css({
'border': '10px solid rgba(186, 0, 0, 0.2)'
});
$('.search-box').css({
'background-color': 'rgba(186, 0, 0, 0.5)',
'color': 'rgba(186, 0, 0, 0.5)'
});
});
Upvotes: 1
Reputation: 28513
You can have CSS classes for border and background color. Add / remove them for hover on and off as shown below -
CSS -
.borderClass{border: 10px solid rgba(186, 0, 0, 0.2);}
.backgroundColorClass{background-color: rgba(186, 0, 0, 0.5);
color: rgba(186, 0, 0, 0.5);}
jQuery -
$('#menu_first_home').hover(function(){
//for hover on
$(this).addClass("borderClass");
$('.search-box').addClass("backgroundColorClass");
},function(){
//for hover off
$(this).removeClass("borderClass");
$('.search-box').removeClass("backgroundColorClass");
});
Upvotes: 0