wordpress user wordpress user - 7 months ago 12
Javascript Question

jQuery global var isn't working

I want to declare global variable but it keeps saying

undefined
.

<div class="last">Blah</div>


$(document).ready(function() {
$(document).on('click', '.last', function() {
window.testing = $(this).html();
})
console.log(testing);
})


I tried this too.

$(document).ready(function() {
var testing;
$(document).on('click', '.last', function() {
testing = $(this).html();
})
console.log(testing);
})

Answer

Your code works fine, but not how you are expecting it to. You read the testing variable on load of the DOM, yet you only give it a value after clicking the button. Instead you need a way to read the window.testing variable after it has been set. Here's an example using a button click.

$(document).ready(function() {
  $(document).on('click', '.last', function() {
    window.testing = $(this).html();
  })

  $('button').click(function() {
    console.log(window.testing);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="last">Set</div>
<button>Read</button>

Also note that using global variables is not a good thing to be doing. If you need to allow variables to be used in various places, use a namespace.