Ahmet
Ahmet

Reputation: 314

How to set the global variable in click event?

$(document).ready(function() {

    var x = "";

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

    alert(x);
});

When first alert works, messagebox shows "test". when second alert works, messagebox shows " ".

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

Upvotes: 4

Views: 6817

Answers (3)

Rafael Eyng
Rafael Eyng

Reputation: 4960

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

That said, I would suggest you to try an approach like this:

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 is only setting one global object (app), avoiding polluting the namespace. The problem in your code was that you were trying to set a "global" but that x wasn't a global, but just a local variable.

See a working JSFiddle here

Upvotes: 2

ltalhouarne
ltalhouarne

Reputation: 4636

Your code is working as expected, the first alert is empty because the click trigger hasn't been called:

FIDDLE

$(document).ready(function() {

    var x = "";

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

    alert(x);
});

Upvotes: 0

morissette
morissette

Reputation: 1099

The problem you are experiencing is because of the flow of the program. Your declaration of the variable x makes x global and scoped to the document.ready function.

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

Upvotes: 0

Related Questions