Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hover and class selector

I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:

<div id="menu">
    <div class="menuItem"><a href=#>Bla</a></div>
    <div class="menuItem"><a href=#>Bla</a></div>
    <div class="menuItem"><a href=#>Bla</a></div>
</div>

CSS:

.menuItem{
  display:inline;
  height:30px;
  width:100px;
  background-color:#000;
}

Javascript:

$('.menuItem').hover( function(){
     $(this).css('background-color', '#F00');
},
function(){
     $(this).css('background-color', '#000');
});

EDIT: I forgot to say that I had reasons not to want to use the css way.

And I indeed forgot to check if the DOM was loaded.

like image 463
Pim Jager Avatar asked Nov 09 '08 13:11

Pim Jager


People also ask

How to use hover using jQuery?

The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element. Syntax: $(selector). hover(Function_in, Function_out);

Is hover deprecated in jQuery?

hover() is deprecated #66.

Can you use hover on a div?

To display div element using CSS on hover a tag: First, set the div element invisible i.e display:none;. By using the adjacent sibling selector and hover on a tag to display the div element.


2 Answers

This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)

HTML:

<div id="menu">
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
</div>

CSS:

.menuItem{
  height:30px;
  width:100px;
  background-color:#000;
}
.menuItem:hover {
  background-color:#F00;
}
like image 113
foxy Avatar answered Oct 01 '22 05:10

foxy


I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.

You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.

.menuItem
{
    display: inline;
    background-color: #000;

    /* width and height should not work on inline elements */
    /* if this works, your browser is doing the rendering  */
    /* in quirks mode which will not be compatible with    */
    /* other browsers - but this will not work on touch mobile devices like android */

}
.menuItem a:hover 
{
    background-color:#F00;
}
like image 33
Vincent Robert Avatar answered Oct 01 '22 06:10

Vincent Robert