Skip to content Skip to sidebar Skip to footer

Jquery Plugin Breaks With This.each

I'm writing a plugin and trying to wrap the function inside of an each method but it breaks the plugin. If the block content is not wrapped within 'this.each' plugin works. I under

Solution 1:

Few things;

  1. Assign $(this) to $this and use it inside any function inside your plugin, said in the tutorial, http://docs.jquery.com/Plugins/Authoring.

    returnthis.each(function () {
        var window_height = $(window).height();
        var document_height = $(document).height();
        var hide_lead;
        $this = $(this);
        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop();
            if (!hide_lead) {
                if (scrollTop > (document_height / 2)) {
                    $this.slideDown(options.speedup);
                } else {
                    $this.slideUp(500, function () {
                        //$(this).hide();
                    });
                }
            }
        });
        $this.click(function (e) {
            $(this).parent().parents('div').hide();
            hide_lead = true;
            e.preventDefault();
        });
    });
    
  2. Try to avoid manipulation of parent objects inside your plugin, including $(window), and $(document).

    It is ok to read properties of window and document, but if it is manipulated in your plugin, it will be maniuplated by number of times of your selector.

    In your code, because you use this.each, you are binding scroll function of window several times. For example, $("div").scroll_lead() will bind 'scroll' method to window as many as tags of your document. The same applies to $(document) and all parent elements of plugin target.

  3. If possible and it is your intention, use element scroll method, not window scroll.

    To get scroll value $(el).scrollTop()

    To scroll down, $(el).scrollTop(NUMBER)

    To bind onScroll method, $(el).scroll( functtion() {...} )

Hope it helps

Solution 2:

Firstly, your syntax is incorrect.

each would not exist on this as this is the context of the function, and not an element that jquery knows about.

try $(this).each which would get you closer.

remember Jquery.Each cannot iterrate over something that is not an object or array, so make sure that what you are trying to achieve makes sense.

What are you trying to achieve here?

Post a Comment for "Jquery Plugin Breaks With This.each"