1

I am using this code to add a function when buttons are clicked, but it's not working.

function onClick(){
    console.log("Button pressed.");
    localStorage.counter = ++counter;
    console.log(counter);
}

window.addEventListener('load', function() {
    console.log("Loaded");
    var buttons = document.getElementsByClassName("v-btn v-btn--small theme--dark orange");
    console.log(buttons);
    console.log("buttons.length:")
    console.log(buttons.length);
    var i;
    for(i = 0;i < buttons.length;i++){
        buttons[i].onclick = onClick();
        console.log("Event added")
    }
}, false);

When page loads I only get this in the console: Chrome Console output

Also nothing happens when I click on the buttons. If I debug it with breakpoints in chrome the output will change and it will say that the buttons is empty.

EDIT: The problem is that its not even entering for loop.

EDIT2: The buttons don't appear when load event is called. window.addEventListener('load') is executing too early

Load is called before the page is loaded

Peca21
  • 11
  • 2
  • What does the HTML look like? Do the buttons have the classes listed in `getElementsByClassName`? – RoToRa Feb 08 '21 at 14:34
  • It doesn't enter into loop because `buttons.length` is zero. You are probably targeting wrong classnames in `document.getElementsByClassName()` – Ozgur Sar Feb 08 '21 at 14:57
  • @OzgurSar look at the picture I posted, it's not empty it has 2 buttons in it – Peca21 Feb 08 '21 at 15:03
  • @Peca21 Sorry I didn't notice that section of the image as buttons.length was already showing 0. Do you have any script that modifies the DOM after the page has initially loaded? – Ozgur Sar Feb 08 '21 at 15:12
  • @OzgurSar Website is from my work so I can't show it but yes the things are loading AFTER the page has been loaded. – Peca21 Feb 09 '21 at 12:22
  • @Peca21 please try to run your javascript at the footer and after all other scripts have run. – Ozgur Sar Feb 09 '21 at 12:35
  • @OzgurSar how do I run it after every other script? – Peca21 Feb 09 '21 at 14:22
  • @Peca21 I mean place it in the footer after all the other javascript calls. – Ozgur Sar Feb 09 '21 at 14:24
  • @OzgurSar I am using tampermonkey, I have no access to the website source. I don't know how to place it at the end with tampermonkey. – Peca21 Feb 09 '21 at 14:27
  • @Peca21 Please check my answer. I wrapped your code inside a `setInterval()` function to make sure it is executed 100 miliseconds after the page has loaded. You can try to increase the waiting time in case 100ms is not enough. – Ozgur Sar Feb 09 '21 at 15:03
  • @OzgurSar the problem is its not consistent, sometimes it loads buttons after 1 second sometimes after 10 seconds. ALso I sometimes press the button after less than 10 seconds so i can't use set interval. – Peca21 Feb 09 '21 at 15:19

4 Answers4

0

You are calling onClick while attacching click handler. You just have to provide the function instead of calling it.

HTML:

  <button class="v-btn v-btn--small theme--dark orange">
    Test1
  </button>
  <button class="v-btn v-btn--small theme--dark orange">
    Test2
  </button>

JS:

function onClick(){
    console.log("Button pressed.");
    localStorage.counter = ++counter;
    console.log(counter);
}

window.addEventListener('load', function() {
    console.log("Loaded");
    var buttons = document.getElementsByClassName("v-btn v-btn--small theme--dark orange");
    console.log("buttons.length:")
    console.log(buttons.length);
    var i;
    for(i = 0;i < buttons.length;i++){
        buttons[i].onclick = onClick;
        console.log("Event added")
    }
}, false);
Swaraj Gandhi
  • 682
  • 3
  • 15
0

function onClick(){
    console.log("Button pressed.");
    // localStorage.counter = ++counter;
    // console.log(counter);
}

window.addEventListener('load', function() {
    console.log("Loaded");
    var buttons = document.getElementsByClassName("v-btn v-btn--small theme--dark orange");
    console.log("buttons.length:")
    console.log(buttons.length);
    var i;
    for(i = 0;i < buttons.length;i++){
        buttons[i].addEventListener('click', function () {
          onClick();
        });
        console.log("Event added")
    }
}, false);
  <button class="v-btn v-btn--small theme--dark orange">
    Test1
  </button>
  <button class="v-btn v-btn--small theme--dark orange">
    Test2
  </button>
Scriptkiddy1337
  • 792
  • 4
  • 9
0

In order to make sure that your script runs after all other script has executed you can make use of setInterval(). I set it to 100 miliseconds (which you can see at the bottom. So, your code will wait 100ms after the page has loaded and will then execute.

As proposed in other answers, you should not call onClick when assigning it to an element's event handler. So, I changed that as well.

function onClick(){
    console.log("Button pressed.");
    localStorage.counter = ++counter;
    console.log(counter);
}


window.addEventListener('load', function() {

  var i = setInterval(function ()
  {
    clearInterval(i);
    console.log("Loaded");
    var buttons = document.getElementsByClassName("v-btn v-btn--small theme--dark orange");
    console.log(buttons);
    console.log("buttons.length:")
    console.log(buttons.length);
    var i;
    for(i = 0;i < buttons.length;i++){
        buttons[i].onclick = onClick;
        console.log("Event added")
    }
  }, 100);

}, false);
Ozgur Sar
  • 2,067
  • 2
  • 11
  • 23
0

SOLVED!

I used this to create a sort of a sleep function

const delay = ms => new Promise(res => setTimeout(res, ms));

And then just checked for a button to appear every half a second like this

do {
   buttons = document.getElementsByClassName("v-btn v-btn--small theme--dark orange");
   await delay(500);
} while(!(buttons.length == 2));

From: Here

Full Code Here

Peca21
  • 11
  • 2