0

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?

Sander Schaeffer
  • 2,757
  • 7
  • 28
  • 58

4 Answers4

2

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
});
giorgio
  • 10,111
  • 2
  • 28
  • 41
  • I assume that also applies for the actual code; write it as a variable and re-use that in the functions where it's needed? -> http://pastebin.com/MaLYCMc9 - Thanks! - And second! Why 'jQuery(document).ready(function($)' instead of $(document).ready(function() {}); - Which seems shorter? – Sander Schaeffer Apr 01 '14 at 08:38
  • 1
    yup, looks good! in javascript you can put everything in a variable: a primitive value, object or function. So anything you'd like to use again, put it in a variable! – giorgio Apr 01 '14 at 08:41
2

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');
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Why "$(window).on('resize', reUse).trigger('resize');" instead of $(window).resize(function() { reUse(); }); ? Using .trigger() seems a little overdone, since .resize() is enough? – Sander Schaeffer Apr 01 '14 at 08:46
  • @SanderSchaeffer - It's to trigger the function **both** on pageload and on resize – adeneo Apr 01 '14 at 08:56
1

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);
mguimard
  • 1,881
  • 13
  • 14
1

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);
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35