Home > Mobile >  Button in JavaScript not active / undefined
Button in JavaScript not active / undefined

Time:11-08

I added an event listener to my button and assigned it a variable. However, it is not functioning. The console keeps showing undefined with no code issues at the same time which makes it complex to figure out.

This is the html markup:

<button value="button" id="myBtn">Click to See</button>

Here is the JavaScript declaration for button to call the function "action" on click:

var btn = document.getElementById("myBtn").addEventListener("click", action);

Yet the console shows I got no issues and still shows btn undefined. Don't know how to fix it.

html :

<div>
        <h3>ZooMoji</h3>
        <img src="moji1.jpg" id="pic1">
       <img src="moji2.jpg" id="pic2"> 
       <button value="button" id="myBtn">Click to See</button>
    </div>

JS:

var swap1 = document.getElementById("pic1").src;
var swap2 = document.getElementById("pic2").src;
var btn = document.getElementById("myBtn").addEventListener("click", action);
    
function action() {
   if (swap1.endsWith("moji1.jpg") == true) {
    swap1.src = swap2;
    
   }
   
   
}

CodePudding user response:

It's because you're getting the value of the .addEventListner function and not the actual .getElementById. Do this instead.

let btn = document.getElementById("myBtn");
btn.addEventListener("click", action);

And also scrap those var's they're old and should in 99.9% of cases be replaced by either const or let if you want it to be mutable.

CodePudding user response:

Actually, the event listener will work fine, and the function action will be executed whenever you click the button, try this:

function action() {
  if (swap1.endsWith("moji1.jpg") == true) {
    swap1.src = swap2;
  }

  console.log("the click event is working fine!")
}

The reason why the btn variable is returning undefined is the event listener itself which returns a void, if you are using VS Code try to hover over the btn variable and you would see something like this:

var btn: void

So in order to get an HTMLElement from the btn variable just do that:

var btn = document.getElementById("myBtn"); // returns HTMLElement
btn.addEventListener("click", action); // returns void

function action() {
  if (swap1.endsWith("moji1.jpg") == true) {
    swap1.src = swap2;
  }
}

For more details: EventTarget.addEventListener()

  • Related