Pascal Gerber
Pascal Gerber

Reputation: 85

How to fix jQuery Image Sequence on Scroll

I try to implement a javascript function that animate an image sequence while scrolling.

I try to create the animation with the script from this link: https://www.jqueryscript.net/animation/jQuery-Plugin-To-Create-Image-Sequence-Animation-On-Scroll-Sequencer.html

My problem is that this script is already three years old and does not work with jQuery 3.2.1. But I have to use this much newer jQuery version.

The code of the script looks like this:

/**
 * jQuery-Sequencer
 * https://github.com/skruf/jQuery-sequencer
 *
 * Created by Thomas Låver
 * http://www.laaver.com
 *
 * Version: 2.0.0
 * Requires: jQuery 1.6+
 *
 */

(function($) {

  $.fn.sequencer = function(options, cb) {

    var self = this,
        paths = [],
        load = 0,
        sectionHeight,
        windowHeight,
        currentScroll,
        percentageScroll,
        index;

    if(options.path.substr(-1) === "/") {
      options.path = options.path.substr(0, options.path.length - 1)
    }

    for (var i = 0; i <= options.count; i++) {
      paths.push(options.path + "/" + i + "." + options.ext);
    }

    $("<div class='jquery-sequencer-preload'></div>").appendTo("body").css("display", "none");

    $(paths).each(function() {
      $("<img>").attr("src", this).load(function() {
        $(this).appendTo("div.jquery-sequencer-preload");
        load++;
        if (load === paths.length) {
          cb();
        }
      });
    });

    $(window).scroll(function() {
      sectionHeight = $(self).height();
      windowHeight = $(this).height();
      currentScroll = $(this).scrollTop();
      percentageScroll = 100 * currentScroll / (sectionHeight - windowHeight);
      index = Math.round(percentageScroll / 100 * options.count);
      if(index < options.count) {
        $("img.sequencer").attr("src", paths[index]);
      }
    });

    return this;

  };

}(jQuery));

So I already changed the line 37 from

$("<img>").attr("src", this).load(function() {

to

$("<img>").attr("src", this).on("load", function() {

With this change all my images are loaded but I still get the error message: Uncaught TypeError: cb is not a function

What do I have to change as well, so the script is working again?

Thanks for any tip.

Upvotes: 1

Views: 855

Answers (1)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

cb() is a Callback function will be called once the preloader is done fetching images.

From the example you have linked to, the callback is:

  function() {
    $("div#preload").hide();
  }

which quite simply hides the preloader message.

In context, the plugin is initialised as:

  $("div#images").sequencer({
    count: 128,
    path: "./images",
    ext: "jpg"
  }, function() {
    $("div#preload").hide();
  });

As you have not supplied how you are calling this function, I suspect you are missing this function callback.

Upvotes: 2

Related Questions