-1

I have a problem with very basic js function. I've looked around and found this topic on SO which is very similar but it didn't help me.

So I want to run a function after the div is clicked. My first attempt would cause the function to run without clicking it:

1st attempt

document.getElementsByClassName('button').addEventListener("click", slide());

function slide(){
  x = document.getElementsByClassName('button')[0];
  x.innerHTML = "test123";
}
.button{
  height:60px;
  background-color:darkred;
}
<div class="button" id="button"></div>

Then after adjusting my code to what I read in the answer provided in the topic I linked above I created something like this:

2nd attempt

document.getElementsByClassName('button').addEventListener("click", function(){
 slide();
});

function slide(){
  x = document.getElementsByClassName('button')[0];
  x.innerHTML = "test123";
}
.button{
  height:60px;
  background-color:darkred;
}
<div class="button" id="button"></div>

But then nothing happens at all after clicking the div. I also tried to do it like this:

document.getElementsByClassName('button').addEventListener("click", slide);

But then also nothing happens. Can someone explain me what I am doing wrong? Thank you in advance.

Mamun
  • 66,969
  • 9
  • 47
  • 59
aMJay
  • 2,215
  • 6
  • 22
  • 34
  • As you have an id it is preferable to use it. getElementsByClassName returns a collection, so you would have to index it `[0]` to add a listener to the first element of the collection. – Andy G Feb 28 '18 at 11:55
  • [This](https://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay) is why the first one didn't work, [this](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) is why the second one didn't work. Re the second: Always be sure to check your web console for errors. – T.J. Crowder Feb 28 '18 at 11:55

1 Answers1

3

You have to issues in your code:

  1. You should not execute the function in addEventListener.
  2. getElementsByClassName returns collection. So you have to use proper index when use getElementsByClassName.

document.getElementsByClassName('button')[0].addEventListener("click", slide);

function slide(){
  x = document.getElementsByClassName('button')[0];
  x.innerHTML = "test123";
}
.button{
  height:60px;
  background-color:darkred;
}
<div class="button" id="button"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59