user8758206
user8758206

Reputation: 2191

SImple click a button event every second

I'm trying to be able to perform a 'click' event every second. I can create a function that runs every second, but not actually perform a 'click' event. Is there something daft I'm doing here? Feels like it should be an easy achievement.

I get the following error: "Uncaught TypeError: Cannot read property 'click' of null"

Why is this error occurring, and how can it be fixed? I want to just program the click and not have to click the button manually, and another Stack Overflow post suggested just using .click().

Thanks for any help here...

function click_fn() {
  console.log('button clicked...');
}


function yourFunction(){
    //console.log('testy');
    document.querySelector('tes').click();

    setTimeout(yourFunction, 1000);
}

yourFunction();
<button class='tes' onclick='click_fn()'>test</button>

Upvotes: 1

Views: 59

Answers (2)

ehab
ehab

Reputation: 8064

The error is quite descriptive, document.querySelector('tes') is returning null, and so .click can not be resolved on null, hence the error

"Uncaught TypeError: Cannot read property 'click' of null"

Here is a working snippet (based on JamesT comment)

function click_fn() {
  console.log('button clicked...');
}


function yourFunction(){
    // console.log('testy');
    document.querySelector('.tes').click();

    setTimeout(yourFunction, 1000);
}

yourFunction();
<button class='tes' onclick='click_fn()'>test</button>

Upvotes: 2

mwilson
mwilson

Reputation: 12980

If you're trying to select an element by a class selector you need to prefix it with a .<classname>

function click_fn() {
  console.log('button clicked...');
}


function yourFunction(){
    //console.log('testy');
    document.querySelector('.tes').click(); // Add . prefix

    setTimeout(yourFunction, 1000);
}

yourFunction();
<button class='tes' onclick='click_fn()'>test</button>

Upvotes: 2

Related Questions