Xhynk
Xhynk

Reputation: 13880

jQuery - target previous (identical) divs on hover?

I have 5 divs in a row. They all have 1 background on page load. I want to change the BG of the div hovered, and all previous identical divs. I'm not sure how to go about that

div { style="background: url(images/red)"}

<div class="myDiv">One</div>
<div class="myDiv">Two<div>
<div class="myDiv">Three</div>
<div class="myDiv">Four</div>
<div class="myDiv">Five</div>

so when div THREE above is hovered on, I want divs ONE, TWO, and THREE to have a blue background.

if I did

$('.myDiv').hover(function(){
    $(this).prev('.myDiv').css({...});
});

It would only affect the first previous one. Can anyone point me in the right direction?

Upvotes: 0

Views: 93

Answers (2)

VIDesignz
VIDesignz

Reputation: 4783

kmb385 has the right answer...to expound on his answer, you can unset the backgrounds on mouseout.

FIDDLE

$('.myDiv').on({
    mouseover: function(){
    $(this).prevAll().andSelf().css("background", "red");
    },
    mouseout: function(){
    $('.myDiv').css("background", "");
    }
});

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Here is the Javascript:

$('.myDiv').hover(function(){
    $(this).prevAll('.myDiv').andSelf().css({...});
});

And you also have a mistake in your markup, the second div isn't closed.:

<div class="myDiv">One</div>
<div class="myDiv">Two</div>
<div class="myDiv">Three</div>
<div class="myDiv">Four</div>
<div class="myDiv">Five</div>

Working Example: http://jsfiddle.net/snynL/

Upvotes: 2

Related Questions