Problems with addEventListener

So, in footer I made 2 animated buttons, one to scroll to bottom, and one to display a message with alert(). They both are not working, I think that the problem is in the addEventListener, but there may be some mistakes in css.
Here is the JS snippet:

var scrollToTopBtn = document.getElementById("scrollToTopBtn");
var rootElement = document.documentElement;

function scrollToTop() {
    top: 0,
    behavior: "smooth"
document.getElementById("scrollToTopBtn").scrollToTopBtn.addEventListener("click", scrollToTop);

var clickAlert = document.getElementById("alermic");
function clickerman(){
  alert("Realizat de Plămădeală Maxim.");

clickAlert.addEventListener("click", clickerman);

And here is my codepen:

  1. Check the id.
var btnContainer = document.getElementById("myDIV");

<div class="dropdown" id="myDIV1">
  1. This is malformed.
  .scrollToTopBtn.addEventListener("click", scrollToTop);

You call addEventListener on what getElementById returns.

You already got the element here in the above code.

var scrollToTopBtn = document.getElementById("scrollToTopBtn");

So you just call it on that element.

scrollToTopBtn.addEventListener("click", scrollToTop);
1 Like

still not working. maybe there is another problem

You did not fix the first problem with the id.

there are 2 IDs for two pages, therefore myDIV is for the main page which I have not included in my codepen, and myDIV1 is for PHP, but I don’t think that this is the problem

Well, it is the problem in the Codepen because you are querying for an id on an element that doesn’t exist.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.