How can I set a global variable on a click event?

$(document).ready(function() {

    var x = "";

    $("#anyElement").click(function() {
        x = "test";
        alert(x);
    });

    alert(x);
});

      

When the first alert is triggered, a "test" is displayed in the message window. when the second alert is running, "" is displayed in the message window.

$("#anyElement").click(function() {
    // How can i set the x veriable as "test" here
});

      

+3


source to share


3 answers


The problem you are facing is with the program flow. Your variable declaration x makes x global and tied to the document.ready function.



'test' is not assigned to the variable x until after the click event and the first warning there is actually a second warning written in code, because there is no event associated with the warning.

0


source


Your code works as expected, the first warning is empty because the click trigger was not called:

FIDDLE



$(document).ready(function() {

    var x = "";

    $("#anyElement").click(function() {
        x = "test";
        alert(x);
    });

    alert(x);
});

      

0


source


I'm not sure if I understand what you are asking for, but hey, let's avoid globals, shall we?

However, I suggest you try this approach:

var app = {};
app.x = 'initial value';

app.bindEvents = function() {
    $('#anyElement').click(function() {
        app.x = 'test';
        console.log(app.x);
    });    
};
app.bindEvents = function() {
    app.bind();
};
$(app.init);

      

Here, our code sets only one global object ( app

), avoiding namespace contamination. The problem in your code was that you tried to set "global", but x

it was not global, but just a local variable.

See working JSFiddle here

0


source







All Articles