Cookies en Outbook

Esta web utiliza cookies propias para ofrecer una mejor experiencia. Al navegar, aceptas dichas cookies.
  • Más información acerca de las cookies

Outbook

UI-Dev & more

Javascript: Carrusel / Slideshow con Jquery

Hace un par de años publiqué un slideshow con Jquery, que tuvo buena acogida y resultó bastante útil. Hace poco lo he estado rehaciendo, en forma de plugin Jquery. Además el código es más legible y se añade la posibilidad de tener controles para ver los elementos ‘Anterior’ y ‘Siguiente’.

Características:

  • Plugin de Jquery
  • Accesible: los controles no tienen dependencia de dispositivo, permiten pausar e ir a slides concretos.
  • Si no hay Javascript se le puede dar estilo para que no se vea mal el contenido.
  • Posibilidad de mostrar dos o más bloques en un solo slide.

Cómo aplicarlo

Ver ejemplo funcional.

HTML

Tan sencillo como un elemento contenedor y los elementos de cada slide. Dentro de cada slide se podrá meter el código que se quiera.

<div class="slides">
  <article class="slide">[...]</article>
  <article class="slide">[...]</article>
  [Resto de slides]
</div>

Javascript

Salvo el plugin, en el ejemplo se inserta todo dentro de la función de un evento ‘ready’:

jQuery(document).ready(function () {
  [...]
});

Un multi-idioma un poco rudimentario:

// Languages
var languageSetting = 'en';
var languageValue = $('html').eq(0).attr('lang');
if (languageValue) {
  languageSetting = languageValue;
}

var slideCultures = {
  'en': {
    'pause': 'Pause'
    ,'resume': 'Resume'
    ,'previous': 'Previous'
    ,'next': 'Next'
    ,'numberedListIntro': 'Go to:'
    
  }
  ,'es': {
      'pause': 'Pausar'
      ,'resume': 'Continuar'
      ,'previous': 'Anterior'
      ,'next': 'Siguiente'
      ,'numberedListIntro': 'Ir a:'
    }
}

Una primera llamada para el slide:

jQuery.fn.slide({
  selectorSlidesBox: '.slides-1'
  ,textPause:slideCultures[languageSetting]['pause']
  ,textResume:slideCultures[languageSetting]['resume']
  ,textPrevious:'<img src="assets/SL_IMG_controls_previous.png" alt="'+slideCultures[languageSetting]['previous']+'" />'
  ,textNext:'<img src="assets/SL_IMG_controls_next.png" alt="'+slideCultures[languageSetting]['next']+'" />'
  ,textNumberedList:slideCultures[languageSetting]['numberedListIntro']
});

Una segunda llamada, para el slide con dos elementos simultáneos:

jQuery.fn.slide({
  selectorSlidesBox: '.slides-2'
  ,numberSimultaneousSlides:2
  ,insertTranslucentElement:false
  ,textPause:slideCultures[languageSetting]['pause']
  ,textResume:slideCultures[languageSetting]['resume']
  ,textPrevious:slideCultures[languageSetting]['previous']
  ,textNext:slideCultures[languageSetting]['next']
  ,textNumberedList:slideCultures[languageSetting]['numberedListIntro']
});

Y el plugin:

(function($){
  $.fn.slide = function(options){
    var defaults = { // Opciones por defecto
      selectorSlidesBox: '.slides'
      ,selectorSlide: '.slide'
      
      ,selectorActive: '.slide-active'
      ,classesActive: 'slide-active'
      
      ,selectorControlsBox: '.slide-controls'
      ,classesControlsBox: 'slide-controls'
      
      ,selectorNumberedListElement: '.slide-control-element a'
      ,classesNumberedListElement: 'slide-control-element'
      ,selectorNumberedListElementActive: '.slide-control-element-active'
      ,classesNumberedListElementActive: 'slide-control-element-active'
      
      ,selectorNavigationPrevious: '.slide-control-previous a'
      ,classesNavigationPrevious: 'slide-control-previous'
      ,selectorNavigationNext: '.slide-control-next a'
      ,classesNavigationNext: 'slide-control-next'
      
      ,selectorControlsPauseResume: '.slide-pause-or-resume'
      ,classesControlsPauseResume: 'slide-pause-or-resume'
      ,classesSliderPaused: 'slide-paused'
      ,classesSliderPlaying: 'slide-playing'
      
      ,classClearfix: 'clear'
      ,classesIndented: 'indented'
      
      ,classesTranslucentElement: 'slide-translucent'
      
      ,slideTime: 3 // In seconds
      ,effectTime: 150 // In miliseconds
      ,numberSimultaneousSlides: 1 // Simultaneous visible elements
      ,insertTranslucentElement: true // Insert translucent element: true or false
      ,translucentElement: '<div></div>'
      ,prefixId: 'jquery-slide-'
      
      // Text params
      ,textPause: 'Pause'
      ,textResume: 'Resume'
      ,textPrevious: 'Previous'
      ,textNext: 'Next'
      ,textNumberedList: 'Go to:'
    }
    var op = $.extend(defaults, options);
    
    init();
    
    function init () {
      
      $(op.selectorSlidesBox).each(function (index) {
        var slidesBox = $(this);
        var slides = slidesBox.find(op.selectorSlide);
        var slidesCount = slides.length;
        var numberId = index;
        var idSlideBox = op.prefixId+(index+1);
        while ($('#'+idSlideBox).length) {
          index++;
          idSlideBox = op.prefixId+(index+1);
        }
        
        
        slidesBox.attr('id',idSlideBox)
        setSlides(slidesBox,slides,idSlideBox); // Activate initial slides, and hide all other
        
        controls(slidesBox,slides,idSlideBox); // Play-Pause and slide number controls
        
      });
      
    }
    
    function startSlide (slidesBox) {
      
      var slideControlsBox = slidesBox.find(op.selectorControlsBox).eq(0);
      var slideControls = slideControlsBox.find(op.selectorNumberedListElement);
      
      var slidePauseResume = slideControlsBox.find(op.selectorControlsPauseResume).eq(0);
      
      var intervalTime = op.slideTime*1000;
      var interval = setInterval(function () {
        changeSlide(slideControlsBox,1);
      },intervalTime);
      
      goToNextAndPrevious (slideControlsBox,interval,slidePauseResume);
      
      slideControls.bind('click',function (event) {
        event.preventDefault();
        pauseSlide(interval,slidePauseResume);
        goToSlide($(this),$(this).attr('data-destination'),slideControlsBox);
      });
      
      slidePauseResume.bind('click',function (event) {
        event.preventDefault();
        if (slidePauseResume.hasClass(op.classesSliderPlaying)) {
          pauseSlide(interval,slidePauseResume);
        } else {
          slidePauseResume.removeClass(op.classesSliderPaused).addClass(op.classesSliderPlaying).html(op.textPause);
          resumeSlide(slidesBox,slideControls,slidePauseResume);
        }
      })
      
    }
    
    function goToNextAndPrevious (slideControlsBox,interval,slidePauseResume) {
      slideControlsBox.find(op.selectorNavigationPrevious).eq(0).bind('click',function (event) {
        event.preventDefault();
        pauseSlide(interval,slidePauseResume);
        changeSlide(slideControlsBox,-1);
      });
      slideControlsBox.find(op.selectorNavigationNext).eq(0).bind('click',function (event) {
        event.preventDefault();
        pauseSlide(interval,slidePauseResume);
        changeSlide(slideControlsBox,1);
      });
    }
    
    function goToSlide (link,destination,slideControlsBox) {
      slideControlsBox.find(op.selectorNumberedListElementActive).removeClass(op.classesNumberedListElementActive);
      link.closest('li').addClass(op.classesNumberedListElementActive)
      
      var activeSlides = $(destination).siblings(op.selectorActive);
      
      
      
      if ($(destination).is(':hidden')) {
        activeSlides.removeClass(op.classesActive).fadeOut(op.effectTime,function() {
          if (op.numberSimultaneousSlides>1) {
            var nextDestination = $(destination).next();
            var i=1; while (i<op.numberSimultaneousSlides) {
              nextDestination.addClass(op.classesActive);
              var nextDestination = nextDestination.next();
              i++;
            }
          }
          $(destination).addClass(op.classesActive).add($(destination).siblings(op.selectorActive)).fadeIn(op.effectTime);
        });
      }
      
    }
    
    function resumeSlide (slidesBox,slideControls,slidePauseResume) {
      slideControls.add(slidePauseResume).unbind('click');
      startSlide(slidesBox);
    }
    
    function pauseSlide (interval,slidePauseResume) {
      clearInterval(interval);
      slidePauseResume.removeClass(op.classesSliderPlaying).addClass(op.classesSliderPaused).html(op.textResume);
    }
    
    function changeSlide (slideControlsBox,direction) {
      var selectedInNumberedList = slideControlsBox.find(op.selectorNumberedListElementActive).eq(0);
      
      if (direction>0) {
        if (selectedInNumberedList.is(':last-child')) {
          var newSelectedInNumberedList = selectedInNumberedList.siblings().eq(0);
        } else {
          var newSelectedInNumberedList = selectedInNumberedList.next();
        }
      } else {
        if (selectedInNumberedList.is(':first-child')) {
          var newSelectedInNumberedList = selectedInNumberedList.siblings().last();
        } else {
          var newSelectedInNumberedList = selectedInNumberedList.prev();
        }
      }
      
      var link = newSelectedInNumberedList.find('a').eq(0);
      var destination = link.attr('data-destination')
      goToSlide(link,destination,slideControlsBox);
    }
    
    function controls (slidesBox,slides,idSlideBox) {
      var controlsBox = $('<div></div>').addClass(op.classesControlsBox);
      var controlsBoxNavigation = $('<nav></nav>');
      generatePauseResume(controlsBoxNavigation); // Creates paragraph with intro text
      generateNumberedList(controlsBoxNavigation,slides,idSlideBox); // Creates numbered list of slides
      controlsBox.append(controlsBoxNavigation);
      slidesBox.append(controlsBox);
      startSlide(slidesBox);
    }
    
    function generateNextAndPrevious (controlsBoxNavigation,firstDestination,lastDestination) {
      var list = $('<ul></ul>');
      generateNextAndPreviousLink(list,op.textPrevious,op.classesNavigationPrevious,lastDestination); // generate 'previous' link
      generateNextAndPreviousLink(list,op.textNext,op.classesNavigationNext,firstDestination); // generate 'next' link
      controlsBoxNavigation.append(list);
    }
    
    function generateNextAndPreviousLink (list,linkText,classes,destination) {
      var link = $('<a></a>').attr({'href':'#','data-destination77':destination}).html(linkText);
      var listElement = $('<li></li>').addClass(classes).append(link);
      list.append(listElement);
    }
    
    function generateNumberedList (controlsBox,slides,idSlideBox) {
      
      
      var numberOfPages = Math.ceil(slides.length/op.numberSimultaneousSlides);
      var list = $('<ul></ul>').addClass(op.classClearfix)
      
      var i=0;
      while (i<numberOfPages) {
        var firstSlide = (((i+1)*op.numberSimultaneousSlides)-op.numberSimultaneousSlides)+1;
        
        var listElement = $('<li></li>');
        var linkDestination = '#'+idSlideBox+'-'+firstSlide+'';
        if (i==0) {listElement.addClass(op.classesNumberedListElementActive);}
        if (i==1) {var firstDestination = linkDestination;}
          
        var lastDestination = linkDestination;
        listElement.html('<a href="#" data-destination="'+linkDestination+'">'+(i+1)+'</a>');
        listElement.addClass(op.classesNumberedListElement);
        list.append(listElement);
        i++;
      }
      generateNextAndPrevious(controlsBox,firstDestination,lastDestination) // Creates 'next' and 'previous' links
      controlsBox.append(list);
    }
    
    function generatePauseResume (controlsBox) {
      var pauseResumeLink = $('<a></a>').addClass(op.classesControlsPauseResume+' '+op.classesSliderPlaying).attr('href','#').html(op.textPause);
      
      var listIntro = $('<span></span>').addClass(op.classesIndented).html(op.textNumberedList);
      
      var listIntroBox = $('<p></p>').append(pauseResumeLink,listIntro)
      
      controlsBox.append(listIntroBox);
    }
    
    function generateTranslucentElement (slide) {
      var translucentElement = $(op.translucentElement).addClass(op.classesTranslucentElement);
      slide.append(translucentElement);
    }
    
    function setSlides (slidesBox,slides,idSlideBox) {
      slides.each(function (index) {
        var slide = $(this);
        slide.attr('id',idSlideBox+'-'+(index+1));
        if (op.insertTranslucentElement) {generateTranslucentElement(slide);}
      });
      activateInitialSlides(slidesBox);
      hideNotInitialSlides(slidesBox);
    }
    
    function activateInitialSlides (slidesBox) {
      var initialSlides = slidesBox.find(op.selectorSlide+':lt('+op.numberSimultaneousSlides+')');
      initialSlides.addClass(op.classesActive);
    }
    
    function hideNotInitialSlides (slidesBox) {
      var notInitialSlides = slidesBox.find(op.selectorSlide+':gt('+(op.numberSimultaneousSlides-1)+')');
      notInitialSlides.hide();
    }
  }
})(jQuery);

Publicado

Categorías: