1

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!

5
  • What are you expecting? What isn't working? Commented Sep 5, 2013 at 15:53
  • 2
    It will alert undefined as the alert() will get executed before the click event happens Commented Sep 5, 2013 at 15:54
  • 1
    This isn't scope-related, it's time-related. The alert will execute when its encountered, the click handler will set x only after the click event. Commented Sep 5, 2013 at 15:59
  • I think there needs to be some clarification. If you want the alert to happen on #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? Commented Sep 5, 2013 at 16:02
  • To clarify, I basically need x to be accessible by other scripts. So once the button is clicked, and x is set, I need to be able to use x in other pages etc. The alert in the code is just for example. But I need to manipulate the value set by the button click event in a different page. Commented Sep 5, 2013 at 16:10

2 Answers 2

1

You are doing correctly, in your code <script> alert(x);</script> when you are using alert x value is not set.

HTML:

<button id="set">set</button>
<button id="get">get</button>

JS:

var x;
$(document).ready(function () {
    $(document).on("click", "#set", function () {
        x = "hello world";
    });

    $(document).on("click", "#get", function () {
        alert(x);
    });
});

JSFiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

1

for that alert to alert Hello World you need to add it inside the click function... since x is redeclare inside the click event . and you don't have to seperate your <script>.

<script>
var x;
$(document).ready(function() {
    $(document).on("click", "#btn", function() {
       x = "hello world";
       alert(x); //alerts hello world
    });
    alert(x); //alerts undefined since x is not set as this is executed before the click event as soon as document is ready
});
alert(x); //alerts undefined since x is not set


</script>    

1 Comment

yup!!! thanks update... i guess. its time for me to go for a coffee :)...thanks @smerny

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.