Domanda

I want to swap an image every time the page is changed using the iDangerous Swiper jQuery plugin.

The page may be changed by dragging between views with a finger or using mySwiper.swipePrev() in code. Every time it is changed I need to change an images's src which shows which page is being displayed. There are only 2 different views.

HTML:

<!-- Source should change based on which page you are on -->
<img class="navbar" src="navbar-firstpage.png" />

<!-- First page -->
<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide" data-hash="page1">
            Slide 1
            <p onClick="mySwiper.swipeNext()">Go to next page</p>
        </div>
    </div>
</div>

<!-- second page -->
<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide" data-hash="page2">
            Slide 1
            <p onClick="mySwiper.swipePrev()">Go to last page</p>
        </div>
    </div>
</div>

jQuery:

// enable swipe between views
var mySwiper = new Swiper('.swiper-container',{
});

My first thought was to call another function within mySwiper.swipeNext(), but this seems to only be called when clicking the text, not when swiping.

Is there a way that I can listen for when the page changes or a hack I can use to detect when an element (ie. something on page 1 or 2) is displayed in the view port with jQuery?

È stato utile?

Soluzione

I was able to do a bit of a hack to detect the page change.

Swiper adds the CSS class swiper-slide-active to the active page, so I am checking if a slide has that class and if so changing the image to reflect this page change.

var mySwiper = new Swiper('.swiper-container',{
    onSlideChangeEnd : function(swiperHere) {
        changeNav();
        var swiperPage = mySwiper.activeSlide()
        console.log(swiperPage);
    }
});
function changeNav() {
    if ($('#pageTwo').hasClass("swiper-slide-active")) { 
        console.log('page is 2');
        $('.navbar').attr("src","navbar-secondpage.png");
    }
    else {
        console.log('page is 1');
        $('.navbar').attr("src","navbar-firstpage.png");
    }
};

If you have more than one page you could use a try catch statement.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top