Open a Script and close another

Asked

Viewed 17 times

1

Hello! I found a slide script, and it supports to move the images vertically and horizontally. In case I put 2 buttons for the user to choose and make the change... when I click vertically or horizontally it works normal, but when one of the two is selected and switched to another, it is the 2 rotating. How do I stop when clicking on each other?

The slide site: http://idangero.us/swiper/

<li><a href="#!" id="horizontal">Horizontal</a></li>
  <li><a href="#!" id="vertical">Vertical</a></li>

$("#vertical").click(function(){
    var swiper = new Swiper('.swiper-container', {
      direction: 'vertical',
      zoom: true,
      scrollbar: {
        el: '.swiper-scrollbar',
        hide: true,
      },
      });
    });
    $("#horizontal").click(function(){
        var swiper = new Swiper('.swiper-container', {
          zoom: true,
          scrollbar: {
            el: '.swiper-scrollbar',
            hide: true,
          },
          });
        });

1 answer

1


You must use the method destroy (plugin doc) from the plugin to remove it from the DOM and then create it again with the desired direction.

Do not use var within the functions to create the plugin instance, otherwise it will become inaccessible in the other function.

$("#vertical").click(function(){
   swiper.destroy();
   swiper = new Swiper('.swiper-container', {
      zoom: true,
      direction: 'vertical',
      scrollbar: {
         el: '.swiper-scrollbar',
         hide: true,
      }
   });
 });

$("#horizontal").click(function(){
   swiper.destroy();
   swiper = new Swiper('.swiper-container', {
      zoom: true,
      scrollbar: {
         el: '.swiper-scrollbar',
         hide: true,
      }
   });
});

Another code option

You can create a function for this, not to repeat the code, taking the direction by id of the button clicked:

function destroiSwiper(dir){
   swiper.destroy();
   swiper = new Swiper('.swiper-container', {
      zoom: true,
      direction: dir,
      scrollbar: {
         el: '.swiper-scrollbar',
         hide: true,
      }
   });
}

$("#vertical, #horizontal").click(function(e){
   destroiSwiper( e.target.id );
});
  • Look, it worked! Thanks Mt!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.