Gray out divs Using JQuery

WillingLearner picture WillingLearner · Jan 21, 2011 · Viewed 17.9k times · Source

Im trying to use this code:

<script>
jQuery('#MySelectorDiv').fadeTo(500,0.2);
</script>

To fade out a bunch of divs named MySelectorDiv, the only thing is, it only fades out the 1st one instead of all of them... why is that?

I also would like to unfade the div on rollover, so basically all divs would be grayed out except for the active one being rolled over.

Hope you understand.

Answer

Darko Z picture Darko Z · Jan 21, 2011

only the first one is being faded because you are using an ID instead of a class.

If you want all your divs to fade out then instead of doing this:

<div id="MySelectorDiv">...</div>

do this:

<div class="MySelectorDiv">...</div>

and change your jquery selector string to '.MySelectorDiv'

The reason it doesnt work currently is because ID are supposed to be unique on the page, therefore jQuery wont bother finding all the elements, just the first one that matches that ID.

As for fading on hover:

$(".MySelectorDiv")
    .fadeTo(500, 0.2)
    .hover(function () {
        $(this).fadeTo(500, 1);
    }, function () {
        $(this).fadeTo(500, 0.2);
    });

This first fades your divs, then attaches a hover event on them - where the first function is run when the mouse enters the area and the second function is run when your mouse leaves the area.