Emerson Maningo
Emerson Maningo

Reputation: 2269

Bind .position() function to $(window).resize() event

I have fully working jQuery code below that uses UI position plugin to position icons in a webpage based on offsets,etc.

While this one is working, I encounter some issues when resizing the browser and that the icon positions are not being recalculated. How to bind .position() function to $(window).resize() event for the code below?

(function($) {
$(window).load(function(event) {


if ( $(element_selector).length !== 0 && $(title_class_selector).length !== 0  ) {

$(title_class_selector).position({
my: "center",
at: cornerPosition,
    offset:"<?php echo $x_coordinates_foradjustment;?> <?php echo $y_coordinates_foradjustment;?>",
of: $(element_selector)

});
}

    });
})(jQuery);

I have tried putting:

$(window).bind('resize',event);

Just before closing jQuery and it did not help. Thanks for any tips..

Upvotes: 0

Views: 766

Answers (1)

Klaas Leussink
Klaas Leussink

Reputation: 2727

I suggest you move the position handling to a seperate function, and then bind that function to both the load and resize events:

var doPosition = function(e) {
    if ( $(element_selector).length !== 0 && $(title_class_selector).length !== 0  ) {

        $(title_class_selector).position({
            my: "center",
            at: cornerPosition,
            offset:"<?php echo $x_coordinates_foradjustment;?> <?php echo $y_coordinates_foradjustment;?>",
            of: $(element_selector)

        });
    }
};

$(window)
.load(doPosition)
.resize(doPosition);

NB: I strongly suggest you debounce the resize event, or it will fire lots of times. This means that when the user has stopped resizing, the event will fire once instead of lots of times during resizing. See more here http://www.hnldesign.nl/blog/debouncing-events-with-jquery/

I created a simple fiddle (using an alert instead of your position calculating stuff, to show it works), with debouncing, over here

Upvotes: 3

Related Questions