Grow your CSS skills. Land your dream job.

Multiple instances of jquery plugin on one page

  • # November 4, 2011 at 5:39 pm

    I’m writing a plugin that activates when you scroll and it works great, but I want to use it twice on one page, but it only seems that when I initialize the 2nd time it overwrites the first one. For example:

    $('#elem').initPlugin({
    id : elem,
    color : 'red',
    height : '500px'
    })

    $('#elem2').initPlugin({
    id : elem2,
    color : 'blue',
    height : '200px'
    })

    In this case, when you scroll, only ‘elem2′ gets styled and ‘elem’ gets skipped over. Here is a layout of my code:

    $.fn.theName = function(options) {
    return this.each(function(){
    settings = $.extend({
    option1: 'etc',
    option2: 'etc',
    //more options
    }, options);

    // code to do stuff

    });
    };
    # November 5, 2011 at 1:49 pm

    Hi noahgelman!

    It would make it much easier to help you if you shared a demo – jsFiddle.net.

    But for now, I would say make sure that the “this” inside of the each function is saved and used as a base when targeting the elements within it. Something like this:

    $.fn.theName = function(options) {
    return this.each(function(){
    settings = $.extend({
    option1: 'etc',
    option2: 'etc',
    //more options
    }, options);

    // code to do stuff
    $this = $(this);

    // target elements inside using $this as the base
    var element = $this.find('.inside');

    });
    };
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".