kodejuice Posted December 7, 2014 Share Posted December 7, 2014 Please i need help toggling between two functions, here is my attempt.<script> toggle = true; function toggleFunc(fn1, fn2){ if(toggle == true){ fn1.call(fn1); toggle = false; } else{ fn2.call(fn2); toggle = true; } }</script>This works perfect, but i can't have more than one "toggleFunc" function on a page. Link to comment Share on other sites More sharing options...
JamesB Posted December 7, 2014 Share Posted December 7, 2014 toggledFunctions = {};function toggleFunc(name, fn1, fn2){ if(toggledFunctions[name]) { fn1.call(fn1); toggledFunctions[name] = false; } else { fn2.call(fn2); toggledFunctions[name] = true; }} // toggleFunc('test1', func1, func2); 1 Link to comment Share on other sites More sharing options...
Ingolme Posted December 7, 2014 Share Posted December 7, 2014 I'm not sure what you're toggling. If you're changing the DOM then there's probably a property in the DOM that tells you what state you're in and you only need one function. Here's an example of toggling the display of an element function toggleDisplay() { var element = document.getElementById("myElement"); if(element.style.display == "none") { element.style.display = ""; } else { element.style.display = "none"; }} I hardly ever see a need for actually toggling between two different functions, there probably is a better solution to your problem but to create that solution we need to know the specifics of your poblem. If it really is necessary to toggle between two functions here's a way to avoid global variables: function Toggle(f1, f2) { var toggle = false; this.run = function() { if(toggle) { f2(); } else { f1(); } toggle = !toggle; }}// How to use it:var t = new Toggle(show, hide);t.run(); // Calls show()t.run(); // Now calls hide() Link to comment Share on other sites More sharing options...
kodejuice Posted December 16, 2014 Author Share Posted December 16, 2014 toggledFunctions = {};function toggleFunc(name, fn1, fn2){ if(toggledFunctions[name]) { fn1.call(fn1); toggledFunctions[name] = false; } else { fn2.call(fn2); toggledFunctions[name] = true; }} // toggleFunc('test1', func1, func2); Thanks a lot, fixed my problem Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now