简体   繁体   中英

Writing and compiling a simple jQuery plugin

I am trying to compile a basic jQuery plugin which shows a div upon provided options when invoking:

  • select if a checkbox should be checked after X milliseconds or after X px on scroll,
  • if one of those two options are selected, set a delay value or scroll distance in px
  • otherwise do nothing

Example of desired options invoke:

    $(document).ready( function() {
        $('#testInput').testing({
            myMethod      : delay,
            myValue       : 2000
        });
});

My current progress here: JSFiddle (it's not much as currently I'm still at a beginning of the learning curve)

After some fiddling i managed to get this working (kinda). Plugin seems to be working fine. Except there is some bug with the scroll function which i have to sort it out additionaly - it loops and changes checkbox states indefinitely instead just once.

Here is a working fiddle

And modified code:

(function($) {

$.fn.testing = function( options ) {

    // Settings
    var settings = $.extend({
        delay           : null,
        delayTime       : null,
        scrolling       : null,
        scrollDist      : null
    }, options);

    return this.each( function() {
        var self = this;

        // Timeout
        setTimeout(function (){
           $(self).prop('checked', settings.delay);
        }, settings.delayTime);

        // Scroll
       if ($(window).scrollTop() > settings.scrollDist) {
          $(this).prop('checked', settings.scrolling);
       };

    });

}

}(jQuery));

// Plugin invoke
$(window).on("load resize scroll",function(){
    $('#testInput').testing({
        delay             : false,
        delayTime         : null,
        scrolling         : true,
        scrollDist        : 20,
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM