0

Can I add css property to elements hover state.

I know how to add background to an element, what I need is to add background to an elements :hover state.

I have a <div class="myDiv"></div>

I can add css background $('.myDiv').css('background', 'red');

When using ('.myDiv').hover((function(e) { $(this).css('background', 'red'); the background changes on hover, but it stays this way even when not hovering over element.

Any ideas?

3
  • Is there a reason you're looking to do this with javascript? Is there an unknown factor stopping you from using css's :hover selector? Commented Apr 10, 2015 at 9:23
  • Generally, applying styles using JavaScript is a bad practise. Please do use CSS’ :hover selector or add/remove classes. Commented Apr 10, 2015 at 9:24
  • Yes there is a reason, as I am generating background with js. Commented Apr 10, 2015 at 10:45

6 Answers 6

7

.hover() method binds handlers for both mouseenter and mouseleave events.You can use it to simply apply behavior to an element during the time the mouse is within the element.

$('.myDiv').hover(function(e) { $(this).css('background', 'red'); },
                 function() { $(this).css('background', 'none'); } );

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

hm, that's probably something with my code..though .mouseenter and .mouseleave works just fine..
1

You can implement it using css no need for any script,

.myDiv:hover {
  background: red;
}
<div class="myDiv">Hello</div>

Comments

0

Try using the mouseenter and mouseleave events instead. Or write your current code like this:

('.myDiv').hover((function(e) { $(this).toggleClass('redBackground') });

Here you have to define the css class 'redBackground'.

Comments

0

hover function comprises two state. hover state and hover out state.

$('.myDiv').hover(
    function() {
        $(this).css('background', 'red');
    }, function() {
        $(this).css('background', 'white')
    }
);

For more info check this link.

Comments

0

Even you can use jQuery mouseenter and mouseleave events. Working Demo

$( ".myDiv" ).mouseenter(function() {
  $( this ).css("background","red");  
});
$( ".myDiv" ).mouseleave(function() {
  $( this ).css("background","none");  
});

2 Comments

could you please explain how this adds any value against any of the previous answers?
This seem to work, while having .hover with two functions inside won't work in my case (not sure why) but would probably be a better solution.
0

Simply use css.No need any jquery.

.myDiv:hover { 
    background-color: #FF0000;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.