Blacky Wolf Blacky Wolf - 5 months ago 10
jQuery Question

How do I change each slide's data- attribute without setting every slide to one background?

I'm working on adding specific

data-
attributes to my slideshow so I can add custom backgrounds for each slide. What I do is add the custom data attribute, then assign the value to a variable using jQuery. After that, I pass the variable to the
.css()
and assign it to the
background
property.



var elementSection = $(".cycle-slideshow section")),
sectionBackground = elementSection.attr("data-cycle-slide-background");

$(elementSection).css({background: sectionBackground});

<section data-cycle-slide-background="url(images/slides/laptopgreenery.jpg)"></section>
<section data-cycle-slide-background="url(images/slides/slide1bg.jpg)"></section>
<section data-cycle-slide-background="url(images/slides/slide2bg.png) repeat;" data-cycle-hash="2"></section>





However, doing it this way sets every slide's background to the one in the attribute, in this case "laptopgreenery.jpg".

Answer

You should loop over each slide:

elementSection.each(function() {
    $(this).css('background', $(this).data('cycle-slide-background'));
});

Important: make sure you don't have ; at the end of data attributes, it will make rule invalid and it will not be applied.

Demo: http://jsfiddle.net/vetnLr8n/

Comments