Home > Software design >  addEventListener not working on specific item
addEventListener not working on specific item

Time:11-24

I have a few instances of addEventListner in my code, and they seem to work alright, but when I use it on this specific portion it does nothing. I'm trying to test it with a simple alert so that when you click the text box on first name, an alert pops up at the top, but right now I'm getting nothing. Here is my for the name box and my addEventListener call:

  <div class="_form_element _x77561130 _full_width " >
    <div class="_field-wrapper form__input-wrapper form__input-wrapper--labelled">
      <input class="form__field form__field--large form__field--text" type="text" id="fname" name="firstname" placeholder="" />
      <label class="_form-label form__floating-label">
        First Name
      </label>
    </div>      
  </div>

and this is my call:

document.getElementById("fname").addEventListener("click", function() {
    alert("Hello World!");  
});

CodePudding user response:

There's not a lot of detail to go on here - but an easy thing to forget is to wrap your JS in a function that checks if either the window or document has loaded so that it doesn't fire before the elements exist. It would be helpful to provide any console errors.

window.addEventListener('load',function(){
 /* add your code here */
}

Check out this answer.

CodePudding user response:

Your code works in the snippet below, so maybe the error is somewhere else.

document.getElementById("fname").addEventListener("click", function() {
    alert("Hello World!");  
});
<div class="_form_element _x77561130 _full_width " >
    <div class="_field-wrapper form__input-wrapper form__input-wrapper--labelled">
      <input class="form__field form__field--large form__field--text" type="text" id="fname" name="firstname" placeholder="" />
      <label class="_form-label form__floating-label">
        First Name
      </label>
    </div>      
  </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related