I would like to make a button that when clicked it would perform action 1 of onclick and when it clicked again it would perform action 2 and after clicking again would make 1, and so on.
I would like to make a button that when clicked it would perform action 1 of onclick and when it clicked again it would perform action 2 and after clicking again would make 1, and so on.
There are N ways to accomplish this functionality. I'll illustrate using a data-attribute
to the HTML element to define / synchronize which action should be performed.
As in the example below.
function test(element)
{
if (element.getAttribute('data-action') == 1)
{
alert("Executando a ação 1...");
element.setAttribute('data-action' , 2);
}
else
{
alert("Executando a ação 2...");
element.setAttribute('data-action' , 1);
}
}
<a href="#" data-action="1" onclick="test(this);" >ação</a>
The data-action
attribute defines which action to execute. The teste
function, after executing the action, changes the data-action
to the next action that will be executed.
Update
As described in the comments, what the author wants is a "toggle" effect. To switch between visible and non-visible.
function toggle(id)
{
document.getElementById(id).classList.toggle('hide');
}
.hide
{
display: none;
}
<a href="#" onclick="toggle('element-id');" >alternar</a>
<div id="element-id" >elemento</div>
Basically the function will validate if in the list of class
of element there is class
hide
. If it exists, it will remove it. Otherwise, you will add it.
The class hide
, in turn, sets the display
of the element to none
. It's best to use class
, instead of directly changing display
, because some elements may have a specific display, which will be lost if you do not save it when you add it back to the element.
You can add a variable to serve as a flag, which gets true / false, or clicked, null, anyway.
As he clicks the button, you make the necessary checks, and change the flag.
But as our friend commented, depending on what you want to do, there are more practical methods.
Guilherme, follow a suggestion for this, using JavaScript:
HTML:
<input id="botao" type="button" onclick="Funcao1();>
Javascript:
function Funcao1(){
// Faz o que você precisa
// Altera a função do click para a função 2
document.getElementById("botao").setAttribute( "onClick", "javascript: Funcao2();" );
}
function Funcao2(){
// Faz o que você precisa
// Altera a função do click para a função 1
document.getElementById("botao").setAttribute( "onClick", "javascript: Funcao1();" );
}