Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gray out divs Using JQuery

Tags:

jquery

fadeout

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.

like image 222
WillingLearner Avatar asked Jan 21 '11 02:01

WillingLearner


Video Answer


2 Answers

Because you're using an ID, not a class. IDs must be unique on a page, while classes may be repeated. Just change all your divs to use a class="myselectordiv" instead of an id. Your jQuery selector would then change to:

jQuery('.myselectordiv')...

To get the rollover effect:

// Fade everything out first
jQuery('.myselectordiv').fadeTo(500, 0.2);
jQuery('.myselectordiv').hover(function () {
    // Mouse enter, fade in
    jQuery(this).fadeTo(500, 1);
}, function () {
    // Mouse leave, fade out
    jQuery(this).fadeTo(500, 0.2);
});

This binds two functions to your divs, one for mouseenter and one for mouseleave, and as you can see they do opposite fadeTos to each other.

Note: there's a subtle problem with this however, which you'll notice if you move your mouse over the divs rather quickly. Even after moving your mouse off the div, if it was still fading it, it will continue to complete the animation before it fades out again. This may be what you want, but if you move your mouse quickly between two divs, they will both continuously fade in and out afterwards because a long queue of animation effects have piled up. To prevent this, add a .stop() before each fadeTo() inside the hover:

jQuery(this).stop().fadeTo(500, 1);

Demo: http://jsfiddle.net/mm8Fv/

like image 196
David Tang Avatar answered Oct 12 '22 16:10

David Tang


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.

like image 39
Darko Z Avatar answered Oct 12 '22 17:10

Darko Z