Search code examples
jquerycssdomjquery-cycle2

Toggle a body class based on active slide using Cycle2


Hi Stack Overflow peeps,

I don't have working code for this, as I'm unsure where to even begin. So apologies in advance.

I've scoured the internet for a solution but this feels like it could either be really simple (and I'm over complicating things) or it's somewhat specialised.


Current Situation: I'm using Cycle2 as my slider of choice (and would prefer to stick with that - will be difficult to make me go with another slider, TBH). Each slide will have a specific "colour" class, as well as a 'slide' class

What I need: I need to change a class on the <body> based on the active class' colour.

Thoughts: So I don't have a naming convention yet for the colour classes, but my thought was it could be something like .col-[name] were [name] is yellow, red, etc. So when the active class of the slider is col-yellow, it adds this class to the <body>, and therefore I can add a background colour/image (whatever CSS I want) to the body.

Then once the active slide changes and if it happens to change its body class to something like col-red, then the <body> matches.

I hope this makes sense and is something some awesome person out in Stack Overflow land can help me with.


Thanks for taking the time to read this!


Solution

  • I answered a similar question not that long ago.

    DEMO http://jsfiddle.net/kevinPHPkevin/7VzaQ/3/

    $('.cycle-slideshow').on('cycle-before', function (event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
    var bg = $(incomingSlideEl).find('img').css('backgroundColor');
    $('body').css('background', bg);
    });
    

    Hope this helps

    [edited] I've edited the code so now it assigns the same class to the body that is assigned to the active slide

    DEMO http://jsfiddle.net/kevinPHPkevin/7VzaQ/4/

    Just to explain what i did - As you can see in the above code i creat a var called bg. This var is the CSS background color of the active slide. I then assign that var to the background of the body tag. As you requested you wanted a class change, not just a style change. In light of this i simply changed the code so that it is finding the attr class rather than the CSS background color.

    Var Snippet before:

    var bg = $(incomingSlideEl).find('img').css('backgroundColor');
        $('body').css('background', bg);
    

    Var snippet after:

    var bg = $(incomingSlideEl).find('img').attr('class');
    $('body').attr('class', bg);