Jump to content

Toggle between two functions - JS


Recommended Posts

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

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

  • 2 weeks later...

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...