Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing the text of a button using javascript event listener

I have a simple button that when clicked, the text on the button will change using a event listener. However, I want to add some logic to the code so that when I click it again it just goes back to the original text. I am fairly new to javascript and trying to advance my skills.

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Event Listeners JS</title>
 </head>

 <body>
   <button>Click Me</button>

   <script>
     document.querySelector("button").addEventListener("click", (e) => {
       e.target.textContent = "I was clicked"; //Changes click me to I was
     });
   </script>
 </body>
</html>

like image 460
Soccerplayer97 Avatar asked Feb 26 '26 12:02

Soccerplayer97


2 Answers

as @Taplar suggested :

EDIT: to make it even cleaner you can single line if statement:

document.querySelector("button").addEventListener("click", (e) => {

    (e.target.textContent === 'Click Me') ? e.target.textContent = "I was clicked" : e.target.textContent = "Click Me"

});

Older answer without single line if statement:

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Event Listeners JS</title>
 </head>

 <body>
   <button>Click Me</button>

   <script>
     document.querySelector("button").addEventListener("click", (e) => {
       //checking the text content in the button if its Click Me
       if(e.target.textContent === 'Click Me'){
       e.target.textContent = "I was clicked"; //Changes click me to I was
         //if its not Click Me it will change back to Click Me
         } else {
           e.target.textContent = "Click Me"; //change back to Click Me
         }
     });
   </script>
 </body>
</html>

like image 53
Elna Haim Avatar answered Feb 28 '26 00:02

Elna Haim


The idea is this:

     document.querySelector("button").addEventListener("click", (e) => {
        let textContent = e.target.textContent;
        if (textContent == "Click Me") {
            e.target.textContent = "I was clicked";
         }
         else {
           e.target.textContent = "Click Me";

         }
     });
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Event Listeners JS</title>
 </head>

 <body>
   <button>Click Me</button>

 </body>
</html>
like image 44
VL93 Avatar answered Feb 28 '26 02:02

VL93