Search code examples
jquerybackgroundstylescycleattr

Change Background Color with Slides jQuery Cycle2


I am using the Cycle2 plugin (http://jquery.malsup.com/cycle2/) for some sliders on a site, and need to detect an inline style from each image contained within the current slide, and then pass that to a parent div in order to change the background color of the area surrounding the slider with each slide.

The output from the slider is like so:

<div class="cycle-slideshow" data-cycle-fx="fade" data-cycle-timeout="0" data-cycle-slides="div" data-cycle-prev="#previous" data-cycle-next="#next" data-cycle-swipe="true" data-cycle-pager="#no-template-pager" data-cycle-pager-template="" style="position: relative;">
<div class="cycle-sentinel cycle-slide" style="position: static; top: 0px; left: 0px; z-index: 100; opacity: 1; visibility: hidden; display: block;">
    <a href="#"><img style="background-color: #ff0000;" src="http://cambelt.co/1070x400/Rotator1?color=cccccc,ffffff" alt="fsadfsdfas"></a>
</div>
<div class="slide cycle-slide cycle-slide-active" style="position: absolute; top: 0px; left: 0px; z-index: 100; opacity: 1;">
    <a href="#"><img style="background-color: #ff0000;" src="http://cambelt.co/1070x400/Rotator1?color=cccccc,ffffff" alt="fsadfsdfas"></a>
</div>
<div class="slide cycle-slide" style="position: absolute; top: 0px; left: 0px; z-index: 99; display: none;">
    <a href="#"><img src="http://cambelt.co/1070x400/Rotator2?color=cccccc,ffffff" alt=""></a>
</div>
<div class="slide cycle-slide" style="position: absolute; top: 0px; left: 0px; z-index: 97; display: none;">
    <a href="#"><img src="http://cambelt.co/1070x400/Rotator3?color=cccccc,ffffff" alt=""></a></div>
<div class="slide cycle-slide" style="position: absolute; top: 0px; left: 0px; z-index: 96; display: none;"><a href="#"><img src="http://cambelt.co/1070x400/Rotator4?color=cccccc,ffffff" alt=""></a>
</div>
</div>

My parent div sits above the slider (.home-rotator-wrap) and spans the width of the window. So far I have this, but am fairly sure that I am way off.

$('.home-rotator-wrap > .cycle-slide-active > img').cycle(function() {
    var slideBG = $(this).attr('style');
    $('.home-rotator-wrap').attr('style', slideBG);
});

Solution

  • First of all, you need to set the 'data-cycle-timeout' to something else than 0, the images weren't showing at all. Here's the code:

    $('.cycle-slideshow').on('cycle-before', function (event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
        var bg = $(incomingSlideEl).find('img').css('backgroundColor'); // get background style from each image
        $('body').css('background', bg); // set background color from var
    });
    

    Demo, JSFiddle