rjf0909
rjf0909

Reputation: 183

How to change css of previous siblings

I am trying to change previous elements when one is hovered on, so when a div with class item is hovered the rest of the divs with item change to smaller size except that one. Could somebody help me figure out how to select all of the previous elements with jquery.

This is the jquery I'm trying to use-

$("div.item").hover.prevAll().css('opacity', '.4')
$("div.item").hover.prevAll().css('width', '10%')

Html

<div id="parent">
  <div class="item">
    <img width="100%" height="100px;" style="background:#000; float: left;"/>
    <div class="child">
      info
    </div>
  </div>
  <div class="item">
  </div>
  <div class="item">
  </div>
</div>

Upvotes: 0

Views: 535

Answers (6)

KnowHowSolutions
KnowHowSolutions

Reputation: 680

Don't use any javascript, you can do this with just CSS.

#parent:hover div.item { opacity:0.4;width:10%;}
#parent div.item:hover { opacity:1;width:100%;}

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 78006

Rest of the divs, or the previous ones? Previous ones use prevAll(), rest of the divs use siblings(). In any regard, you should try to keep the CSS rules out of your JavaScript and reference a CSS class when possible.

CSS:

.item.hovered {
    opacity : .4;
    width   : 10%;
}

jQuery:

$('div.item').hover(function() {
    $(this).prevAll().toggleClass('hovered');
});

Demo with previous divs: http://jsfiddle.net/Q89R7/

Demo with all siblings: http://jsfiddle.net/2F3Ae/

Upvotes: 3

sangram parmar
sangram parmar

Reputation: 8736

try this

DEMO

Jquery

  $("div.item").hover(function () {     
      $("div.item").css('opacity', '.4');
      $("div.item").css('width', '10%');
      $(this).css('opacity', '1');
      $(this).css('width', '10%');
  })

Upvotes: 1

GautamD31
GautamD31

Reputation: 28753

Try like this

$("div.item").hover(function(){
   $(this).prevAll().css({'opacity': '4','width':'10%'})
});

Or you can try individual properties like

$(this).prevAll().css('opacity','4');
$(this).prevAll().css('width','10%');

Upvotes: 2

bipen
bipen

Reputation: 36541

to change for rest of the divs you need to use siblings() , prevAll() gets all the elements which is present before that element. try this.

 $("div.item").hover(function(){
   $(this).siblings().css({'opacity': '.4',width:'10%'})
}, function(){
   $(this).siblings().css({opacity: 1,width: ''});
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

You need

$("div.item").hover(function(){
    $(this).siblings().css({
        opacity: '.4',
        width: '10%'
    });
}, function(){
    $(this).siblings().css({
        opacity: 1,
        width: ''
    });
})

Demo: Fiddle

Upvotes: 1

Related Questions