.addEventListener is not a function why does this error occur?
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment
is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName
returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
why btn.addEventListener is not a function. i am stuck in this problem and couldn't find any solution .anyone can help me?
the getElementsByClassName
return an array of elements (cf doc).
to get the first element you should either get the first element of the array document.getElementsByClassName("btn")[0];
or add an id to the button and get it with the document.getElementById('myButton')
function
const btn = document.getElementsByClassName("btn")[0];
const color = document.getElementsByClassName("color")
btn.addEventListener('click', function() {
const randomNumber = getRandomNumber();
document.body.style.backgroundColor = colors[randomNumber]
color.textContent = color[randomNumber]
})
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>
showing error -- addEventListener is not a function
You can always use console.log()
in function to print what is getting returned from specific api or you can use debugger
keyword to debug your script.
<!DOCTYPE html>
<html>
<head>
<title>JS+DOM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<p class="second">No Excuse</p>
<ul>
<button>Click Me!</button>
<li class ="bold red"random="23">Notebook</li>
<li>jello</li>
<li>spanish</li>
<li>rice</li>
<li>birthday cake</li>
</ul>
</body>
<script>
var boton = document.getElementsByTagName("button");
/* if you have multiple button, you can loop over elements as getElementsByTagName returns an array*/
boton[0].addEventListener("click",res); // this will fix the error
function res(){
console.log("Hello");
}
</script>
</html>
Uncaught typeError : input.addEventListener is not a function
According to
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
document.querySelectorAll returns a nodeList which is an array. So you can't assign eventListener to all of them that way. You have to
input.forEach( inp => inp.addEventListener(...))
How to fix .addEventListener is not a function
As previously noted querySelectorAll
will return a nodelist rather than a specific node and thus assigning an event listener as you do will not work. Instead the nodelist should be iterated through and the event listener applied to each node. The idea of using a shortcut to document.querySelectorAll
is one I do frequently but they are a little different as shown below. The remains of the code can be simplified a little ...
(function () {
"use strict";
var q=(e,n=document)=>n.querySelector(e);
var qa=(e,n=document)=>n.querySelectorAll(e);
var view = q(".result_");
var btns = qa(".combine_");
let clickhandler=(e)=>{
e.preventDefault();
let a=Number( q(".enter_1").value );
let b=Number( q(".enter_2").value );
let c;
switch(e.target.dataset.combine){
case 'plus':c=a+b;break;
case 'minus':c=a-b;break;
case 'multi':c=a*b;break;
case 'divi':c=a/b;break;
}
view.textContent=c.toString();
};
btns.forEach( btn=>btn.addEventListener("click", clickhandler ) );
})();
<!-- try run this -->
<div class="input_wrpr">
<input name='a' class="enter_1" type="number" />
<input name='b' class="enter_2" type="number" />
<button data-combine="plus" class="combine_ plus" type="submit"> + </button>
<button data-combine="minus" class="combine_ minus" type="submit"> - </button>
<button data-combine="multi" class="combine_ multi" type="submit"> * </button>
<button data-combine="divi" class="combine_ divi" type="submit"> / </button>
<p class="result_"></p>
</div>
.addEventListener is not a function ERROR
Only individual elements have addEventListener
methods. You need to get .getElementsByClassName("orderPizza")[0]
.
x.addEventListener is not a function?
Since document.getElementsByTagName()
returns a collection of elements as opposed to a single element so you would have to iterate over them. Example:
var buttons = document.getElementsByTagName('button'); // get the buttons
for (var i = 0; i < buttons.length; i++) { // loop over them
buttons[i].addEventListener('click', function(e) {
// your event code here
}); // add event listener to each one
}
Note that this will also apply the event listener to the Start
button (since it is also a button), so if you wish to prevent that, you would add an id
attribute to the root <table>
element (example: <table id="button_table">
) and use
like so:
Element.getElementsByTagName()
var button_table = document.getElementById('button_table');
var buttons = button_table.getElementsByTagName('button');
TypeError: $(...).addEventListener is not a function
As a comment pointed out, You are trying to use the "vanilla" javascript way to add an eventlistener on a jQuery object.
$.clickOverlay = function(whichOverlay) {
var flag = 0;
$("#runtime-overlay"+whichOverlay).addEventListener("mousedown", function(){
flag = 0;
}, false);
$("#runtime-overlay"+whichOverlay).addEventListener("mousemove", function(){
flag = 1;
}, false);
$("#runtime-overlay"+whichOverlay).addEventListener("mouseup", function(){
if(flag === 0){
console.log("click");
}
else if(flag === 1){
console.log("drag");
}
}, false);
}
instead try:
$.clickOverlay = function(whichOverlay) {
var flag = 0;
$("#runtime-overlay"+whichOverlay).on("mousedown", function(){
flag = 0;
});
$("#runtime-overlay"+whichOverlay).on("mousemove", function(){
flag = 1;
});
$("#runtime-overlay"+whichOverlay).on("mouseup", function(){
if(flag === 0){
console.log("click");
}
else if(flag === 1){
console.log("drag");
}
});
}
Related Topics
Creating Drop Down Menu on Click CSS
Change the Style of an Entire CSS Class Using JavaScript
Appending Form Input Value to Action Url as Path
Open a New Tab with JavaScript But Stay on Current Tab
How to Change the Font (Family) for the Labels in Chart.Js
Div Z-Index Issue with Flash Movie
How to Load Images to User's Cache Asynchronously
JavaScript Code Works in Jsfiddle and But Not in the Browser
Storing Image Data for Offline Web Application (Client-Side Storage Database)
What Are Some Methods to Debug JavaScript Inside of a Uiwebview
How to Position a Div in a Specific Coordinates
Save and Render a Webpage with Phantomjs and Node.Js
Invoke Native Date Picker from Web-App on iOS/Android
How to Clear a Chart from a Canvas So That Hover Events Cannot Be Triggered
Createelement VS. Createelementns
Jquery Change Event on an <Input> Element - Any Way to Retain Previous Value
Doing Links Like Twitter, Hash-Bang #! Url'S
Why Is the Variable Holding the Input Value Always Logged as Empty