views:

161

answers:

3

I am using the following code to apply a hover effect to a set of images within a div called toolbar:

$("#toolbar img").hover(
    function()
    {
        this.src = this.src.replace("_off", "_on");
    },
    function()
    {
        this.src = this.src.replace("_on", "_off");
    }
);

But I also want to apply the same effect to a div called tabs without repeating the same code. cant I do something along these lines:

$("#toolbar, #tabs img").hover(
    function()
    {
        this.src = this.src.replace("_off", "_on");
    },
    function()
    {
        this.src = this.src.replace("_on", "_off");
    }
);

The problem is the above only applies to the "tabs" div, while the toolbar stops working. I think I am just getting the jQuery syntax wrong, still sorta new to jQuery

+5  A: 

You separate multiple selectors by commas as you did. If you want to recreate the effect as it was in the first example it needs to be:

$("#toolbar img, #tabs img")

'#toolbar img' is the entire selector. It says "apply this to any img tags that are in a parent element with the id of toolbar". E.g.:

<div id ="toolbar">
   <img .../>
   <img .../>
</div>

#tabs img, is a whole other selector.

These are the same syntax as CSS selectors, so for more information research that.

geofflane
thanks, that's what I was looking for
Neil N
+1  A: 

Try $("#toolbar img, #tabs img").

SLaks
+1  A: 

Shouldn't there be "#toolbar img, #tabs" instead of "#toolbar, #tabs img" ?

Thinker