Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change an if-else statement into a toggle?

I have black text that when double clicked, changes to a different color. I want it to be able to change back to black on a double click. Right now, I have:

<script>
<h1 id="color"> I CHANGE COLORS! </h1>
<a href="javascript:void(0)" ondblclick="
        counter++;
        if(counter%2==1){color()} else {black()}
        ">Double click here</a>
</script>

The two functions called are color() and black(). Is there anyway I can use a toggle instead of this if-else with javascript?

like image 986
Jay Avatar asked Jan 21 '26 02:01

Jay


1 Answers

Store the functions in a globally accessible object:

functions = {};
functions[true] = black;
functions[false] = color;

black = true

And then invert your state flag:

<a href="javascript:void(0)" ondblclick="
        black = !black;
        functions[black]();
        ">Double click here</a>

While this satisfies your very arbitrary requirements, it's a hideous solution.

like image 69
meagar Avatar answered Jan 23 '26 14:01

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!