Blacky Wolf Blacky Wolf - 1 year ago 62
jQuery Question

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

I'm working on adding specific

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
and assign it to the

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 Source

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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download