How to toggle between two onclick function | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
+ 7

How to toggle between two onclick function

Example - I made a div which on click moves 250px to left after moving when I click on it again I want it to move right 250px (toggle between left and right)

7th Feb 2017, 11:57 AM
UtkőĪrsh - avatar
5 Respostas
+ 5
You can say that if the x position is .... or more move to the left, else move to the right. So you get the position of the element and compare it to the top position you choose
7th Feb 2017, 12:41 PM
C.E. - avatar
+ 5
thanks it worked
7th Feb 2017, 12:43 PM
UtkőĪrsh - avatar
+ 5
To handle switching ( or rotating select if more than two ) of function each time you call it ( ie. on an event statement ), you can use this snippet-object: function FuncSwitch(...f) { var count=f.length; var state=0; if (count<2) throw 'Invalid arguments number for [FuncSwitch] object: '+count+' ( require at least 2 functions )'; else if (count==2) { { if (state=!state) f[0](...args); else f[1](...args); } } else { state=-1; var func=[]; for (var i in f) func.push(f[i]); { func[++state%func.length](...args); } } } Basic example of use: function fa() { alert('fa'); } function fb() { alert('fb'); } function fc() { alert('fc'); } var fs1=new FuncSwitch(fa,fb);;;;; var fs2=new FuncSwitch(fa,fb,fc);;;;; Sample of integration: <div onclick=";'> <!-- if you have a global var fs=new FuncSwitch(...); --> var fs=new FuncSwitch(/*...*/); var e=document.getElementById('anId');; /* OR */ e.addEventListener('click',;
7th Feb 2017, 1:21 PM
visph - avatar
+ 3
create a variable to hold the increment you want to add to the position var shift = 250; function updatePosn(){//function for the onclick event shift = 250* -1; //invert increment position+=shift;//update position }
7th Feb 2017, 12:22 PM
seamiki - avatar
+ 2
One way to do this would be to simply add a variable to check If the button has already been clicked. You could for example start with a integer of value 0 and add 1 to It when the user clicks the button, and then you can use a if-else to move the div to the opposite direction based on the number contained by that variable (which would let you know how many times the button has been clicked and by that its actual position). Another way would be to simply check the position before moving the div (you can see how to do that on the course) and after that use an if-else to move to the other direction.
7th Feb 2017, 12:24 PM