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
});
source to share
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.
source to share
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
source to share