Search code examples
jqueryjquery-cycle2

Changing CSS when Slide Changes in Cycle2


http://jsfiddle.net/gS8LE/

The effect that I'm going for is when a slide is active, the corresponding slide button (outside of the slideshow container) changes CSS.

I hope this will make the site easier to understand for users; to see a slide and a corresponding change of buttons.

HTML

<!-- BUTTON -->
<a href="#" data-cycle-context=".mySlideshows" 
            data-cycle-cmd="goto" 
            data-cycle-arg="0"> SLIDE 0 
</a>

<!-- SLIDE -->
<div class="mySlideshows" data-cycle-slides="> div">
    <div id="slide-0"> SOME TEXT </div>

CSS
.active { color: red; }

JS
$( '.mySlideshows' ).cycle(

    // Can I change the active CSS rule 
    // here with Cycle's options?

    // When SLIDE 0 is active
    // Change  to have the active class (.active)

);

Solution

  • Using Cycle 2's pager functionality to handle this would be the simplest approach. It's really flexible and shouldn't require you specify the pager template on every slide for something like this. Here's the example html:

    <div class="mySlideshows">
        <div><p>Slide text...</p></div>
        <div><p>Slide text...</p></div>
        <div><p>Slide text...</p></div>
    </div>
    
    <ul id="custom-pager"></ul>
    

    the JavaScript:

    $('.mySlideshows').cycle({
        slides: '> div',
        pager: '#custom-pager',
        pagerTemplate: '<li><a href="">Slide {{slideNum}}</a></li>',
        pagerActiveClass: 'active'
    });
    

    and an updated fiddle: http://jsfiddle.net/gS8LE/5/

    This works well if you just need your pager links to just show the slide number. However it can be easily modified to also show custom text in the pager link for each slide. You just need to put a data attribute onto your slides. It can be called anything so long as it starts with 'data-cycle-'. Here's the modified html for that:

    <div class="mySlideshows">
        <div data-cycle-pager-title="Custom link text">
            <p>Slide text...</p>
        </div>
        <div data-cycle-pager-title="Another link">
            <p>Slide text...</p>
        </div>
        <div data-cycle-pager-title="Final link">
            <p>Slide text...</p>
        </div>
    </div>
    

    the updated JavaScript:

    $('.mySlideshows').cycle({
        slides: '> div',
        pager: '#custom-pager',
        pagerTemplate: '<li><a href="">{{pagerTitle}}</a></li>',
        pagerActiveClass: 'active'
    });
    

    and here's a fiddle for this setup: http://jsfiddle.net/gS8LE/4/