21

I've this code:

<script>
            $(document).ready(function larg(){
            var larghezza = $(document).width();
            $("p.width").text("The width for the " + larghezza + 
                " is px.");
            });

            $(window).resize(function() {
            larg(); 
            });
            </script>

I would like to call the function "larg" on window resize, but it doesn't work.. How to do that??

Thanks

Luca Frank Guarini
  • 1,193
  • 5
  • 13
  • 26

2 Answers2

38

You can't declare functions that way, use it like this.

<script>
 $(document).ready(larg);

 $(window).resize(larg);

 function larg(){
  var larghezza = $(document).width();
  $("p.width").text("The width for the " + larghezza + " is px.");
 }
</script>

EDIT: changed code a bit, thanks commenters

LHolleman
  • 2,486
  • 2
  • 18
  • 19
  • 2
    +1. I think `$(document).ready(larg); $(document).resize(larg); function larg(){ ... }` should also work. – Eddie Apr 25 '12 at 09:27
  • @Eddie Correct. As would `$(window).resize(larg);`. – Anthony Grist Apr 25 '12 at 09:29
  • What about if I want to pass a variable to the function e.g. `function larg(foo){}` I tried `$window.resize(larg(myVar));` but no results. – kile Mar 22 '14 at 18:06
  • Did you declare the var outside the scope of the anonymous functions? It works when you declare it like this: http://jsfiddle.net/UVXF3/ – LHolleman Mar 23 '14 at 10:50
  • Old question, but shouldn't you define the `function` before using it? – Rvervuurt May 18 '16 at 11:28
1

Please call the following method:

window.dispatchEvent(new Event('resize'));
Pang
  • 9,564
  • 146
  • 81
  • 122
Shyam Bhagat
  • 759
  • 6
  • 7