I read through Explaining Javascript Scope and Closures
but I can't seem to get the following code to work. As you can see I have tried a lot of variations, and can't pass in the current value to a function that will be called later.
I want the alert to read "START" not "END" when the div is clicked... help?
var someString = "START";
document.getElementById('elem1').onclick = function(){
return function(someString){
alert(someString);
}();
};
document.getElementById('elem2').onclick = function(){
alert(someString);
};
document.getElementById('elem3').onclick = function(){
alert(new String(someString));
};
document.getElementById('elem4').onclick = function(someString){
return function(someString){
alert(someString);
}();
};
document.getElementById('elem5').onclick = function(someString){
return function(){
alert(someString);
}();
};
document.getElementById('elem6').onclick = function(){
var newSomeString =someString;
alert(newSomeString);
};
var someString = "END";
<body>
<div style="background-color='yellow';display:block;" id="elem1">1</div>
<br>
<div style="background-color='red';display:block;" id="elem2">2</div>
<br>
<div style="background-color='blue';display:block;" id="elem3">3</div>
<br>
<div style="background-color='green';display:block;" id="elem4">4</div>
<br>
<div style="background-color='orange';display:block;" id="elem5">5</div>
<br>
<div style="background-color='pink';display:block;" id="elem6">6</div>
<br>
</body>