0

Tengo una gran duda, quiero hacer una lista de imágenes que se repitan así como esta en el código utilizando jquery puedo clonar los elementos li, pero quiero que a la hora de mostrar los elementos repetidos, salgan en desorden, ahora mismo están saliendo en orden (1,2,3,1,2,3) así sucesivamente, quiero que salga de forma aleatoria (2,1,3,1,3,2,3,1) etc... !

¿Me puede ayudar?

/**
 * Endless Scroll plugin for jQuery
 *
 * v1.4.8
 *
 * Copyright (c) 2008 Fred Wu
 *
 * Dual licensed under the MIT and GPL licenses:
 *   https://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
 * Usage:
 *
 * // using default options
 * $(document).endlessScroll();
 *
 * // using some custom options
 * $(document).endlessScroll({
 *   fireOnce: false,
 *   fireDelay: false,
 *   loader: "<div class=\"loading\"><div>",
 *   callback: function(){
 *     alert("test");
 *   }
 * });
 *
 * Configuration options:
 *
 * bottomPixels  integer          the number of pixels from the bottom of the page that triggers the event
 * fireOnce      boolean          only fire once until the execution of the current event is completed
 * fireDelay     integer          delay the subsequent firing, in milliseconds, 0 or false to disable delay
 * loader        string           the HTML to be displayed during loading
 * data          string|function  plain HTML data, can be either a string or a function that returns a string,
 *                                when passed as a function it accepts one argument: fire sequence (the number
 *                                of times the event triggered during the current page session)
 * insertAfter   string           jQuery selector syntax: where to put the loader as well as the plain HTML data
 * callback      function         callback function, accepts one argument: fire sequence (the number of times
 *                                the event triggered during the current page session)
 * resetCounter  function         resets the fire sequence counter if the function returns true, this function
 *                                could also perform hook actions since it is applied at the start of the event
 * ceaseFire     function         stops the event (no more endless scrolling) if the function returns true
 *
 * Usage tips:
 *
 * The plugin is more useful when used with the callback function, which can then make AJAX calls to retrieve content.
 * The fire sequence argument (for the callback function) is useful for 'pagination'-like features.
 */

(function($){

  $.fn.endlessScroll = function(options) {

    var defaults = {
      bottomPixels: 50,
      fireOnce: true,
      fireDelay: 150,
      loader: "<br />Loading...<br />",
      data: "",
      insertAfter: "div:last",
      resetCounter: function() { return false; },
      callback: function() { return true; },
      ceaseFire: function() { return false; }
    };

    var options = $.extend({}, defaults, options);

    var firing       = true;
    var fired        = false;
    var fireSequence = 0;

    if (options.ceaseFire.apply(this) === true) {
      firing = false;
    }

    if (firing === true) {
      $(this).scroll(function() {
        if (options.ceaseFire.apply(this) === true) {
          firing = false;
          return; // Scroll will still get called, but nothing will happen
        }

        if (this == document || this == window) {
          var is_scrollable = $(document).height() - $(window).height() <= $(window).scrollTop() + options.bottomPixels;
        } else {
          // calculates the actual height of the scrolling container
          var inner_wrap = $(".endless_scroll_inner_wrap", this);
          if (inner_wrap.length == 0) {
            inner_wrap = $(this).wrapInner("<div class=\"endless_scroll_inner_wrap\" />").find(".endless_scroll_inner_wrap");
          }
          var is_scrollable = inner_wrap.length > 0 &&
            (inner_wrap.height() - $(this).height() <= $(this).scrollTop() + options.bottomPixels);
        }

        if (is_scrollable && (options.fireOnce == false || (options.fireOnce == true && fired != true))) {
          if (options.resetCounter.apply(this) === true) fireSequence = 0;

          fired = true;
          fireSequence++;

          $(options.insertAfter).after("<div id=\"endless_scroll_loader\">" + options.loader + "</div>");

          data = typeof options.data == 'function' ? options.data.apply(this, [fireSequence]) : options.data;

          if (data !== false) {
            $(options.insertAfter).after("<div id=\"endless_scroll_data\">" + data + "</div>");
            $("div#endless_scroll_data").hide().fadeIn();
            $("div#endless_scroll_data").removeAttr("id");

            options.callback.apply(this, [fireSequence]);

            if (options.fireDelay !== false || options.fireDelay !== 0) {
              $("body").after("<div id=\"endless_scroll_marker\"></div>");
              // slight delay for preventing event firing twice
              $("div#endless_scroll_marker").fadeTo(options.fireDelay, 1, function() {
                $(this).remove();
                fired = false;
              });
            }
            else {
              fired = false;
            }
          }

          $("div#endless_scroll_loader").remove();
        }
      });
    }
  };

})(jQuery);


// Script
$(document).ready(function() {
    $(document).endlessScroll({
        inflowPixels: 300,
        callback: function() {
      var $img = $('#images li:nth-last-child(5)').clone();
      $('#images').append($img);
        }
    });
});
body {
  margin: 0;
  background-color: #F0F0F0;
  font-family: 'Liberation Sans', Arial, sans-serif;
}

h1 {
  text-align: center;
}

#images {
  margin: 0 auto;
  padding: 0;
  width: 640px;
  list-style-type: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Infinite Scrolling through Images</title>



  <link rel="stylesheet" href="css/style.css">


</head>

<body>

  <h1>Infinite Scrolling, Demo 3</h1>

  <ul id="images">
    <li>
      <a href="https://www.pexels.com/photo/mist-misty-fog-foggy-7919/">
        <img src="https://pexels.imgix.net/photos/7919/pexels-photo.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/landscape-nature-sunset-trees-479/">
        <img src="https://pexels.imgix.net/photos/479/landscape-nature-sunset-trees.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/landscape-sun-trees-path-21008/">
        <img src="https://pexels.imgix.net/photos/21008/pexels-photo.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/cold-snow-landscape-nature-1127/">
        <img src="https://pexels.imgix.net/photos/1127/cold-snow-landscape-nature.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/coastline-aerial-view-sea-9148/">
        <img src="https://pexels.imgix.net/photos/9148/pexels-photo.jpeg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
  </ul>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>



  <script src="js/index.js"></script>




</body>

</html>

1 respuesta 1

1

De la siguiente manera:

Vas a notar que primero calculo la cantidad de imagenes que tenes "cargadas"

var cantidad_imagenes = $('#images li').size();

Luego en base a esa cantidad elijo una posición de alguna de ellas al azar y la guardo en la variable random.

var random = Math.floor(Math.random() * (cantidad_imagenes));

Por ultimo clono la imagen en la pocicion que acabo de calcular y la agregamos al final.

var img =  $('#images').find("li:eq("+random+")").clone();
$('#images').append(img);

A Continuacion la porcion de codigo completa:

$(document).ready(function() {
    var cantidad_imagenes = $('#images li').size();

    $(document).endlessScroll({
      inflowPixels: 300,
      callback: function() {
        var random = Math.floor(Math.random() * (cantidad_imagenes));
        var img =  $('#images').find("li:eq("+random+")").clone();
        $('#images').append(img);
      }
    });
});

Te lo dejo funcionando en un fiddle.

Espero que te haya ayudado.

Saludos.

/**
 * Endless Scroll plugin for jQuery
 *
 * v1.4.8
 *
 * Copyright (c) 2008 Fred Wu
 *
 * Dual licensed under the MIT and GPL licenses:
 *   https://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
 * Usage:
 *
 * // using default options
 * $(document).endlessScroll();
 *
 * // using some custom options
 * $(document).endlessScroll({
 *   fireOnce: false,
 *   fireDelay: false,
 *   loader: "<div class=\"loading\"><div>",
 *   callback: function(){
 *     alert("test");
 *   }
 * });
 *
 * Configuration options:
 *
 * bottomPixels  integer          the number of pixels from the bottom of the page that triggers the event
 * fireOnce      boolean          only fire once until the execution of the current event is completed
 * fireDelay     integer          delay the subsequent firing, in milliseconds, 0 or false to disable delay
 * loader        string           the HTML to be displayed during loading
 * data          string|function  plain HTML data, can be either a string or a function that returns a string,
 *                                when passed as a function it accepts one argument: fire sequence (the number
 *                                of times the event triggered during the current page session)
 * insertAfter   string           jQuery selector syntax: where to put the loader as well as the plain HTML data
 * callback      function         callback function, accepts one argument: fire sequence (the number of times
 *                                the event triggered during the current page session)
 * resetCounter  function         resets the fire sequence counter if the function returns true, this function
 *                                could also perform hook actions since it is applied at the start of the event
 * ceaseFire     function         stops the event (no more endless scrolling) if the function returns true
 *
 * Usage tips:
 *
 * The plugin is more useful when used with the callback function, which can then make AJAX calls to retrieve content.
 * The fire sequence argument (for the callback function) is useful for 'pagination'-like features.
 */

(function($){

  $.fn.endlessScroll = function(options) {

    var defaults = {
      bottomPixels: 50,
      fireOnce: true,
      fireDelay: 150,
      loader: "<br />Loading...<br />",
      data: "",
      insertAfter: "div:last",
      resetCounter: function() { return false; },
      callback: function() { return true; },
      ceaseFire: function() { return false; }
    };

    var options = $.extend({}, defaults, options);

    var firing       = true;
    var fired        = false;
    var fireSequence = 0;

    if (options.ceaseFire.apply(this) === true) {
      firing = false;
    }

    if (firing === true) {
      $(this).scroll(function() {
        if (options.ceaseFire.apply(this) === true) {
          firing = false;
          return; // Scroll will still get called, but nothing will happen
        }

        if (this == document || this == window) {
          var is_scrollable = $(document).height() - $(window).height() <= $(window).scrollTop() + options.bottomPixels;
        } else {
          // calculates the actual height of the scrolling container
          var inner_wrap = $(".endless_scroll_inner_wrap", this);
          if (inner_wrap.length == 0) {
            inner_wrap = $(this).wrapInner("<div class=\"endless_scroll_inner_wrap\" />").find(".endless_scroll_inner_wrap");
          }
          var is_scrollable = inner_wrap.length > 0 &&
            (inner_wrap.height() - $(this).height() <= $(this).scrollTop() + options.bottomPixels);
        }

        if (is_scrollable && (options.fireOnce == false || (options.fireOnce == true && fired != true))) {
          if (options.resetCounter.apply(this) === true) fireSequence = 0;

          fired = true;
          fireSequence++;

          $(options.insertAfter).after("<div id=\"endless_scroll_loader\">" + options.loader + "</div>");

          data = typeof options.data == 'function' ? options.data.apply(this, [fireSequence]) : options.data;

          if (data !== false) {
            $(options.insertAfter).after("<div id=\"endless_scroll_data\">" + data + "</div>");
            $("div#endless_scroll_data").hide().fadeIn();
            $("div#endless_scroll_data").removeAttr("id");

            options.callback.apply(this, [fireSequence]);

            if (options.fireDelay !== false || options.fireDelay !== 0) {
              $("body").after("<div id=\"endless_scroll_marker\"></div>");
              // slight delay for preventing event firing twice
              $("div#endless_scroll_marker").fadeTo(options.fireDelay, 1, function() {
                $(this).remove();
                fired = false;
              });
            }
            else {
              fired = false;
            }
          }

          $("div#endless_scroll_loader").remove();
        }
      });
    }
  };

})(jQuery);


// Script
$(document).ready(function() {
    var cantidad_imagenes = $('#images li').size();

    $(document).endlessScroll({
      inflowPixels: 300,
      callback: function() {
        var random = Math.floor(Math.random() * (cantidad_imagenes));
        var img =  $('#images').find("li:eq("+random+")").clone();
        $('#images').append(img);
      }
    });
});
body {
  margin: 0;
  background-color: #F0F0F0;
  font-family: 'Liberation Sans', Arial, sans-serif;
}

h1 {
  text-align: center;
}

#images {
  margin: 0 auto;
  padding: 0;
  width: 640px;
  list-style-type: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Infinite Scrolling through Images</title>



  <link rel="stylesheet" href="css/style.css">


</head>

<body>

  <h1>Infinite Scrolling, Demo 3</h1>

  <ul id="images">
    <li>
      <a href="https://www.pexels.com/photo/mist-misty-fog-foggy-7919/">
        <img src="https://pexels.imgix.net/photos/7919/pexels-photo.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/landscape-nature-sunset-trees-479/">
        <img src="https://pexels.imgix.net/photos/479/landscape-nature-sunset-trees.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/landscape-sun-trees-path-21008/">
        <img src="https://pexels.imgix.net/photos/21008/pexels-photo.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/cold-snow-landscape-nature-1127/">
        <img src="https://pexels.imgix.net/photos/1127/cold-snow-landscape-nature.jpg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
    <li>
      <a href="https://www.pexels.com/photo/coastline-aerial-view-sea-9148/">
        <img src="https://pexels.imgix.net/photos/9148/pexels-photo.jpeg?fit=crop&w=640&h=480" alt="" />
      </a>
    </li>
  </ul>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>



  <script src="js/index.js"></script>




</body>

</html>

1
  • Muchas gracias aunque ya lo habia resuelto, de otra manera aunque es bueno aprender cosas nuevas y tu me has enseñado algo nuevo, gracias por tu ayuda amigo leonardo espero mejorar para poder ayudar a la gente ! @leonardo cabré ! Commented el 24 ene. 2018 a las 15:23

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.