ctrlmaniac
ctrlmaniac

Reputation: 444

Why does this function returns twice the result?

I got a simple question. Why does this function returns twice the width of only the first element if the function holds a resize function?

var $element1 = $( '.one' ),
    $element2 = $( '.two' );

function Width( element ) {
    $( window ).resize(function() {
        var width = element.width();
        console.log( width );
    });
    $( window ).resize();
}

Width( $element1 );
Width( $element2 );

Is it something wrong with my code?

fiddle http://jsfiddle.net/eLLcZ/

fiddle without the resize function http://jsfiddle.net/VbX8L/

Upvotes: 0

Views: 111

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123573

Using $( window ).resize(); within Width() will invoke all of the window's accumulated resize handlers each time:

Width( $element1 ); // the `window` has 1 `resize` handler, it's invoked
                    // log: 100

Width( $element2 ); // the `window` has 2 `resize` handlers, both are invoked
                    // calling the 1st handler a 2nd time (totaling 3 logs)
                    // log: 100
                    // log: 150

This expansion would continue if you had additional elements (e.g. $element3 at 200px):

Width( $element3 ); // Adds a 3rd handler, invokes the 1st and 2nd again
                    // log: 100
                    // log: 150
                    // log: 200

To only invoke the current handler, at least at the time when it's being bound to the event, you'll want to call it directly rather than triggering the entire event each time:

function Width( element ) {
    function onResize() {
        var width = element.width();
        console.log( width );
    }
    $( window ).resize(onResize); // add for later
    onResize();                   // call once now
}

Width( $element1 ); // log: 100
Width( $element2 ); // log: 150

You can still trigger the entire event later to run through all of the handlers at once:

$( window ).resize(); // log: 100
                      // log: 150

Upvotes: 2

Related Questions