javascript - Variable returns [object HTMLParagraphElement] -


i having difficulties working variables in jquery. var need return width of window. test wrote code width displayed in paragraph when hit 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 "[object htmlparagraphelement]" instead of value of width. don't understand why, because when run 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 value without problems. in way can't update variable after resizing window (i think because variable declared @ loading of page.)

this real newbe problem, eager learn...

'named' elements ids added properties of document. why when calling width before, should have been undefined had not had element

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

since had element, width defaulted [object htmlparagraphelement]

see do dom tree elements ids become global variables?

also, need call update ()

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, above returns value rather use/assign global variable width. better practice avoid anti-patterns.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -