[javascript] 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.

This question is related to javascript jquery html css

The answer is


test.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>jQuery Test</title>
        <link rel="stylesheet" type="text/css" href="test.css" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <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>
    </body>
</html>

test.css

.menuItem
{

    display: inline;
    height: 30px;
    width: 100px;
    background-color: #000;

}

test.js

$( function(){

    $('.menuItem').hover( function(){

        $(this).css('background-color', '#F00');

    },
    function(){

        $(this).css('background-color', '#000');

    });

});

Works :-)


Always keep things easy and simple by creating a class

.bcolor{ background:#F00; }

THEN USE THE addClass() & removeClass() to finish it up


test.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>jQuery Test</title>
        <link rel="stylesheet" type="text/css" href="test.css" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <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>
    </body>
</html>

test.css

.menuItem
{

    display: inline;
    height: 30px;
    width: 100px;
    background-color: #000;

}

test.js

$( function(){

    $('.menuItem').hover( function(){

        $(this).css('background-color', '#F00');

    },
    function(){

        $(this).css('background-color', '#000');

    });

});

Works :-)


Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

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;
}

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;
}

I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery

http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/


I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")


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;
}

On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

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;
}

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;
}

If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:

I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...

function changeAttr(attrName,changeThis,toThis){
    var mysheet=document.styleSheets[1], targetrule;
    var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;

    for (i=0; i<myrules.length; i++){
        if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
            targetrule=myrules[i];
            break;
        }
    }
    switch(changeThis)
    {
        case "height":
            targetrule.style.height=toThis+"px";
            break;
        case "width":
            targetrule.style.width=toThis+"px";
            break;
    }

}

I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery

http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/


Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")


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;
}

On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")


Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

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;
}

test.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>jQuery Test</title>
        <link rel="stylesheet" type="text/css" href="test.css" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <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>
    </body>
</html>

test.css

.menuItem
{

    display: inline;
    height: 30px;
    width: 100px;
    background-color: #000;

}

test.js

$( function(){

    $('.menuItem').hover( function(){

        $(this).css('background-color', '#F00');

    },
    function(){

        $(this).css('background-color', '#000');

    });

});

Works :-)


If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:

I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...

function changeAttr(attrName,changeThis,toThis){
    var mysheet=document.styleSheets[1], targetrule;
    var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;

    for (i=0; i<myrules.length; i++){
        if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
            targetrule=myrules[i];
            break;
        }
    }
    switch(changeThis)
    {
        case "height":
            targetrule.style.height=toThis+"px";
            break;
        case "width":
            targetrule.style.width=toThis+"px";
            break;
    }

}

Always keep things easy and simple by creating a class

.bcolor{ background:#F00; }

THEN USE THE addClass() & removeClass() to finish it up


On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width