Home > Software design >  Add eventlistener only if element exists
Add eventlistener only if element exists

Time:09-26

I want to add eventlistener to a html element. But It creates js error when the element doesn't exist. The element exists only on some pages.

    // (A) ATTACH CLICK LISTENER ON PAGE LOAD
window.addEventListener("load", () => {
  document.getElementById("download_mp3j_0").addEventListener("click", doSomething);
});
// (B) THE USUAL FUNCTION
function doSomething () {
  // (B1) DETACH CLICK LISTENER
  var div = document.getElementById("download_mp3j_0");
  div.removeEventListener("click", doSomething);
  // (B2) EXTRA - CHANGE THE TEXT IF YOU WANT
  div.innerHTML = "Downloading";
  // (B3) DO YOUR PROCESSING HERE
  alert("Downloading!");
  // (B4) RE-ENABLE AFTER PROCESSING IF YOU WANT
  // div.addEventListener("click", doSomething);
}

Basically, the function is to remove the button after it has been clicked, to avoid multiple redundant clicks.

I want the function doSomething to run only if the element download_mp3j_0 exists.

CodePudding user response:

Optional chaining operator

A simple alternative would be to use the Optional chaining (?.) operator:

.getElementById(id)?.addEventListener(...

And the event handler is only attached when the element exists.

You might also use the disable attribute during downloading as this would avoid having to add and remove the existing event handler.

See code snippet for details

window.addEventListener("DOMContentLoaded", function() {

  document.getElementById("download_mp3j_0")?.addEventListener("click", function() {

    let element = this;
    element.value = "Downloading...";
    element.disabled = true;
    element.style.cursor = "wait";

    // simulated download

    window.setTimeout(function() {
      element.value = "Download";
      element.disabled = false;
      element.style.cursor = "default";
    }, 2000);

  })
});
#download_mp3j_0 {
  background-color: steelblue;
  color: white;
}

#download_mp3j_0:disabled {
  background-color: orange;
}
<input type="button" id="download_mp3j_0" value="Download">

CodePudding user response:

Try this :

if (document.getElementById("download_mp3j_0")) { // Check if the element exists
    // Add event listener
}

So it makes :

// (A) ATTACH CLICK LISTENER ON PAGE LOAD ONLY IF THE ELEMENT EXISTS
window.addEventListener("load", () => {
    if (document.getElementById("download_mp3j_0")) {
        document.getElementById("download_mp3j_0").addEventListener("click", doSomething);
    }
});

// (B) THE USUAL FUNCTION
function doSomething() {
    // (B1) DETACH CLICK LISTENER
    var div = document.getElementById("download_mp3j_0");
    div.removeEventListener("click", doSomething);
    // (B2) EXTRA - CHANGE THE TEXT IF YOU WANT
    div.innerHTML = "Downloading";
    // (B3) DO YOUR PROCESSING HERE
    alert("Downloading!");
    // (B4) RE-ENABLE AFTER PROCESSING IF YOU WANT
    // div.addEventListener("click", doSomething);
}
  • Related