Change word by clicking the same word. Javascript

Asked

Viewed 137 times

2

Hi, I searched some scripts, but I could not find any that do what I need, not even in W3school.

However it seems to be very simple, click on a word and it changes to another word and when you click again switch to the original format. For example, Palavra1 when clicking turns to Palavra2 and when clicking on Palavra2 turns to Palavra1, in this loop ai rsrs.

<a href="#palavra" id="palavra" onclick='document.getElementById("palavra").innerHTML = "Palavra2"'>Palavra1</a>

This example he only changes once...

4 answers

2


If only to resolve this situation you can do using ternary operator. Follows code:

<a href="#palavra" id="palavra" onclick='document.getElementById("palavra").innerHTML=(document.getElementById("palavra").innerHTML == "Palavra1") ? "Palavra2" : "Palavra1";'>Palavra1</a>

Syntax:

condition ? Expr1 : expr2

Parameters:

condition - An expression that is evaluated as true or false.

Expr1, expr2 - Expressions with values of any kind.

  • Hi, thanks for the help! I’m new here in the community. Sorry anything.

  • @Gabrielramos count on us. Hug.

2

You don’t need id. Use the this which references the element itself. And as our friend said in his reply, you can use the ternary operator:

<a href="#palavra" onclick='var t = this.textContent; this.textContent = t == "Palavra1" ? "Palavra2" : "Palavra1"'>Palavra1</a>

  • Hi, thanks for the help! I’m new here in the community. Sorry anything.

  • Welcome friend!

2

In your HTML you place a call to the javascript function.

< p onclick='MudaPalavra()' > Palavra1</p>

After, at the top inside ta head or at the end of the file before closing the, add the script tags.

<script>
    function MudaPalavra(){
        if(document.getElementById("palavra").value == "Palavra1")
            document.getElementById("palavra").innerHTML = "Palavra2";
        else
            document.getElementById("palavra").innerHTML = "Palavra1";
    }
</script>
  • Hi, thanks for the help! I’m new here in the community. Sorry anything.

  • Don’t worry Gabriel! I hope I’ve helped.Go posting, your doubts, don’t be afraid to ask for help, just so you can develop. Success!

0

<p id="texto" onclick="mudarPalavra()">Palavra1</p>

<script>
var palavra = false;

function mudarPalavra(){
    if (palavra == false) {
        document.getElementById("texto").innerHTML = "Palavra1";    
        palavra = true;
    } else {
        document.getElementById("texto").innerHTML = "Palavra2";    
        palavra = false;
    }
}
</script>
  • Hi, thanks for the help! I’m new here in the community. Sorry anything.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.