+ 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
Utkαrsh - avatar
5 Réponses
+ 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.
C.E. - avatar
+ 5
thanks it worked
7th Feb 2017, 12:43 PM
Utkαrsh
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) { this.next=function(...args) { if (state=!state) f[0](...args); else f[1](...args); } } else { state=-1; var func=[]; for (var i in f) func.push(f[i]); this.next=function(...args) { 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); fs1.next(); fs1.next(); fs1.next(); fs1.next(); var fs2=new FuncSwitch(fa,fb,fc); fs2.next(); fs2.next(); fs2.next(); fs2.next(); Sample of integration: <div onclick="fs.next();'> <!-- if you have a global var fs=new FuncSwitch(...); --> var fs=new FuncSwitch(/*...*/); var e=document.getElementById('anId'); e.onclick=fs.next; /* OR */ e.addEventListener('click',fs.next);
7th Feb 2017, 1:21 PM
visph
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
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
55socram54