Jquery custom plugin function checks parameters

Suppose I defined a jQuery function, which could be as follows:

jQuery.fn.extend({
  objectParallax: function(speed) {
    var $window = $(window);
    return this.each(function() {
      var elem = $(this);
      var defaultTop = parseInt(elem.css('top'));
      $window.on('scroll', function() {
        var scrolled = $window.scrollTop();
        elem.css('top', (defaultTop - (scrolled * speed)) + 'px');
      });
    })
  }
});

I want the parameter to speedbe a parameter instead of a parameter (my real function is a little more complicated than this, and it has a few more parameters that I also want to become parameters). How can i do this? And how can I check that speedis a number from -2 to 2, and output an error in the console if it is not?

0
source share
1 answer

Now you want to define the options object and pass the object instead of the variable speedand extend the default values ​​with user-defined options

:

jQuery.fn.extend({
  objectParallax: function(options) {

    // plugin defaults
    var defaults = {
      speed: '.5', // expect values between -2 & 2
      /* other properties and default values */   
    };

    // in case no user options object provided make sure we pass object to settings extend
    options = options ? options : {};

    // create settings by extending defaults with user defined opts
    var settings = $.extend({}, defaults, options);

    // ultra basic speed validation
    if (settings.speed < -2 || settings.speed > 2) {
      console.error('Speed not in limits');
      return;  // quit if not valid  
    }   

    var $window = $(window);
    return this.each(function() {
      var elem = $(this);
      var defaultTop = parseInt(elem.css('top'));
      $window.on('scroll', function() {
        var scrolled = $window.scrollTop();
        // use settings properties instead of `speed` argument
        elem.css('top', (defaultTop - (scrolled * settings.speed)) + 'px');
      });
    });
  });
});

pass options, , . /,

var opts = {speed: 1.5 };
$('#floating-parallax-1, #floating-parallax-2').objectParallax(opts);

jQuery Learning Center/Plugins

, jQuery, .

+1

All Articles