Real life example?
^ (Bitwise XOR) as an I/O toggler
JsBin example
Used as value ^= 1 will change each time value called 0, 1, 0, 1 ...
If we pass this value as a Statement to the Conditional operator (?:) , for example,
statement ? (if true) : (if false)
and checking the logical representation 0=false, 1=true , we can switch the text, classes, styles .... all that is needed, for example, ie: button text:
value ? "Close dropdown" : "Open dropdown";
For a single element , the Toggle function might look like this:
// USING GLOBAL VARIABLE var tog = 0; var btn = document.getElementById('myButton'); function toggler(){ tog ^= 1; this.innerHTML = tog ? "hide" : "show"; } btn.addEventListener('click', toggler, false);
For several elements, we can save the state of the tog variable directly in this - ElementHTML Object , for example:
// WITHOUT GLOBAL VARIABLE var btns = document.getElementsByClassName('myButton'); function toggler(){ var tog = this.tog ^= 1; // get/set tog value out of this.tog object this.innerHTML = tog ? "hide" : "show"; } for(var i=0; i<btns .length; i++){ btns[i].addEventListener('click', toggler, false); }
Or, if you don't like the idea of this , select the standard property of the dataset attribute;)
Roko C. Buljan Feb 27 '14 at 6:58 2014-02-27 06:58
source share