Sander Schaeffer
Sander Schaeffer

Reputation: 2827

How do you re-use Javascript scripts?

I've got a calculation script that executes when the page loads, but also when the window gets resized. The code in between is exactly the same; not re-used.

So I was wondering, not if, but how do I re-use Javascript code?

I've tried a few stuff, like the next piece, but that ain't working.

$(function reUse() {
    alert('Either the page got resized or the page loaded!');
    console.log('Either the page got resized or the page loaded!');
});

$(window).resize(function() {
    reUse();
});

So what should be the correct way of formatting?

Upvotes: 0

Views: 63

Answers (4)

adeneo
adeneo

Reputation: 318202

You're missing a few parenthesis etc, and you can just trigger event handlers

$(function() {
    function reUse() {
        alert('Either the page got resized or the page loaded!');
        console.log('Either the page got resized or the page loaded!');
    }

    $(window).on('resize', reUse).trigger('resize');
});

Upvotes: 2

giorgio
giorgio

Reputation: 10202

You should put the function outside of the closure. You are now adding the function as a jQuery object. The way to go would be:

var reUse = function() {
    alert('Either the page got resized or the page loaded!');
    console.log('Either the page got resized or the page loaded!');
};

$(window).resize(function() {
    reUse();
});

And you'll want to wrap it all in a closure:

jQuery(document).ready(function($) {
    // the code above
});

Upvotes: 2

Mehran Hatami
Mehran Hatami

Reputation: 12961

try to make it global, in your scope:

var reUse;
$(reUse = function reUse() {
    alert('Either the page got resized or the page loaded!');
    console.log('Either the page got resized or the page loaded!');
});

$(window).resize(function() {
    reUse();
});

or for the second use, if you don't have any special parameter to pass to your function:

$(window).resize(reUse);

Upvotes: 1

mguimard
mguimard

Reputation: 1891

Write it like this

function reUse() {
    alert('Either the page got resized or the page loaded!');
    console.log('Either the page got resized or the page loaded!');
}

$(window).resize(reUse);

Upvotes: 1

Related Questions