Appropriate way to toggle in Javascript/jQuery without using global variables? -
usually when code toggle function example toggling between 2 background colors, use global variable flag. example -
var flag = true; function change() { if(flag) { document.getelementbyid("box").style.backgroundcolor = "blue"; flag = false; } else { document.getelementbyid("box").style.backgroundcolor = "red"; flag = true; } }
#box { width:100px; height:100px; background-color:red; }
<h3>click box toggle</h1> <div id="box" onclick="change()"></div>
but when code multiple functions toggle various properties, number of global variables increases , stated these articles-
article #1
article #2
article #3
global variables must avoided. question is, other way write simple function toggle?
you can using addeventlistener bind click event in combination self-executing anonymous function.
(function(){ var flag = true; document.getelementbyid('box').addeventlistener('click', function() { this.style.backgroundcolor = flag ? "blue" : "red"; flag = !flag; }); })();
#box { width:100px; height:100px; background-color:red; }
<h3>click box toggle</h1> <div id="box"></div>
Comments
Post a Comment