jquery – Using Cycle2 and "picturefill" together

Question:

I created a responsive slideshow using Cycle2. Since the images are very large, I need to upload a smaller file of each image when the page is opened on mobile devices.

So I thought about using picturefill. But it's hard to reconcile the two plugins. picturefill uses span within span and Cycle2 appears to identify each span as an independent slide.

Answer:

By default, Cycle2's jQuery slides selector is > img (selects only images directly children of .cycle-slideshow ).

You need to change it to match your tag. The picturefill uses span s for each responsive image, so add this attribute to the Cycle2 container :

data-cycle-slides="> span"

Fiddle (yes, I used the same images twice)

In this way, all span s directly from children .cycle-slideshow will be used as slides. Here is the tag used for the demo:

<div class="cycle-slideshow"
    data-cycle-fx="scrollHorz"
    data-cycle-speed="200"
    data-cycle-slides="> span"
    >

    <span data-picture data-alt="Uma foto">
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/small.jpg"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/medium.jpg" data-media="(min-width: 400px)"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/large.jpg" data-media="(min-width: 800px)"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/extralarge.jpg" data-media="(min-width: 1000px)"></span>
    </span>

    <span data-picture data-alt="Uma foto">
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/small.jpg"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/medium.jpg" data-media="(min-width: 400px)"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/large.jpg" data-media="(min-width: 800px)"></span>
        <span data-src="http://scottjehl.github.io/picturefill/external/imgs/extralarge.jpg" data-media="(min-width: 1000px)"></span>
    </span>

</div>

Obs.: I'm not including fallbacks to disabled JS or old IE to make the demo simpler. Add them if necessary.


NOTE: This answer applies to Picturefill version 1.2.x as this was the latest version when this answer was originally written.

Picturefill from version 2.0 on uses the <picture> element, or also <img> with srcset and sizes attributes. In order for Cycle to work with Picturefill 2.x, you will then have to adapt Cycle's slide selector to > picture or > img depending on the syntax used.

Scroll to Top