1

I am having difficulties working with variables in jQuery. The var would need to return the width of the window. To test this I wrote some code where the width is displayed in a paragraph when I hit a button:

var update = function() {
  width = $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        update,
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I get "[object HTMLParagraphElement]" instead of the value of the width. I don't understand why, because when I run this code:

var width = $(window).width();

$(document).ready(
    function () {
        $('button').click(
            function () {
                $('#width').text(width)
            }
        )
    }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I do get the value without any problems. But in this way I can't update the variable after resizing the window (I think because the variable is only declared at the loading of the page.)

This probably is a real newbe problem, but I am very eager to learn...

Biest
  • 35
  • 1
  • 5

1 Answers1

3

'Named' elements with ids are added as properties of document. This is why when you were calling width before, it should have been undefined had you not had this element

<p id="width">Width</p>

Since you had this element, width defaulted to [object HTMLParagraphElement]

See Do DOM tree elements with ids become global variables?

Also, you need to call update with a ()

var update = function() {
  return $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        var width = update();
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

Note, the above returns a value rather than use/assign a global variable width. This is better practice to avoid anti-patterns.

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • And even better, `return` a value from the function instead of assigning to an implicit global. – Bergi May 31 '15 at 12:57