lipenco
lipenco

Reputation: 1368

set image as a background of a sibling element

my goal is to let the user to choose the background, but my js doesn;t work.

<div class="step">
</div>

<div id="images">
  <img src="" data-src="">
  <img src="" data-src="">
  <img src="" data-src="">
  <img src="" data-src="">
</div>

<div class="step">
</div>

<div class="step">
</div>

The images div is dynamic and should always change the image of the .step just before.

here is my buggy js:

$(document).on('click', '#images img', function(){ 
  var src = $(this).data('src'); 
  $(this).before().find('.step').css("background" , "url("+src+")");  
});

Upvotes: 2

Views: 419

Answers (4)

nnnnnn
nnnnnn

Reputation: 150040

The .before() method inserts content, it doesn't find an earlier element. You want the .prev() method, noting that it finds the previous sibling so you need to traverse via the .parent():

$(this).parent().prev().css("background" , "url("+src+")");

Demo: http://jsfiddle.net/DBRkS/

Note that .prev() doesn't search backwards until it finds a matching element, it selects the immediately preceding sibling if it matches the selector you supply, otherwise it returns nothing. So for the html you've shown it would work the same with or without the ".step" selector.

Upvotes: 2

Venkata Krishna
Venkata Krishna

Reputation: 15112

$(this).parent() will give you the div which holds the images & .prev('.step') gives you the previous element with class step. before() is only used to insert before each element in the set of matched elements.

$(this).parent().prev('.step').css("background" , "url("+src+")");

Upvotes: 2

epascarello
epascarello

Reputation: 207511

I think what you are selecting is wrong and before() appends elements.

$(this).parent().prev('.step').css("background" , "url("+src+")"); 

basic explanation

$(this)  //the image
    .parent()  // the div #images 
        .prev('.step')  //get the previous sibling with the class step
            .css("background" , "url("+src+")"); 

If you want all of the .step elements, you would use .siblings(".step") instead of .prev(".step")

Upvotes: 3

andygoestohollywood
andygoestohollywood

Reputation: 1285

I think you want prev(), not before()

Upvotes: 2

Related Questions