I am a newbie to jQuery and am trying to make a variable within a nested function available between scripts. However, I am unsure of how to do so (I am pretty bad at understanding scope). Here is the code (note: I copy-pasted this from jsFiddle, hence some tags are purposefully missing).
<body>
<h1>Hello</h1>
<button id="btn">click</button>
<script>
var x;
$(document).ready(function() {
$(document).on("click", "#btn", function() {
x = "hello world";
});
});
</script>
<script>
alert(x);
</script>
</body>
Any help is appreciated!
undefinedas thealert()will get executed before the click event happensalertwill execute when its encountered, the click handler will setxonly after the click event.#btn's click event, why didn't you put the alert there? If you don't want the alert to happen then, when do you want it to happen?