0

I am writing a small practice website. Relevant HTML:

...
<body>
    <div id="button">CLICK ME</div>
    <script src="assets/js/app.js"></script>
</body>
...

My app.js file has the following code:

document.querySelector("#button").addEventListener("click", new function() {
    alert("test");
});

When I reload the page, the event triggers. After that, clicking the div does nothing. What is causing this issue and how can I fix it?

3 Answers3

2

insead of new function() use only function

document.querySelector("#button").addEventListener("click", function() {
    alert("test");
});
Met Br
  • 556
  • 4
  • 8
2

The second parameter of addEventListener takes a reference to a function. Putting new in front, you create a new object and you apply an anonymous function as constructor. So the return value of it is an object instead of a function, which is what you need.

As such, your code would need to be (as pointed out by Met Byrdy):

document.querySelector("#button").addEventListener("click", function() {
    alert("test");
});

Just for fun though, I will give you a way to actually use new in that context. You can use the new Function syntax to do it:

document.querySelector("#button").addEventListener("click", new Function("alert('dsds')"));

Not that I recommend it, but thought you should know there is a way to write a function like that as well.

Reference: https://javascript.info/new-function

codemonkey
  • 5,572
  • 3
  • 17
  • 30
0

addEventListener takes two arguments, the second argument is the function that you want the listener to invoke every time the event is triggered, in your case "click" event.

When you put "new" in front of the function it changes the function into a constructor function that creates a class instance ( returns an object ). That is why you need to use the function without the new keyword just like below.

document.querySelector("#button").addEventListener("click", function() {
    alert("test");
});

-- Edit --

You can check this stackoverflow issue

Dharman
  • 21,838
  • 18
  • 57
  • 107
Mohib Arshi
  • 344
  • 1
  • 9