seulberg1
seulberg1

Reputation: 1013

Button's onclick works but JS event listener does not

I have the following button:

<input type="button" class ="anhalteButton" id="StopButton" value="&#9611 &#9611"/>

which I want to execute the following function (viewsLoop is a global variable):

function clearTDLoop(){ 

    clearInterval(viewsLoop);
}

If I call the function via the button's onclick attribute. i.e.: onclick="clearTDLoop()" it works flawlessly.

However, I would like to call the function through a JS event listener, but that does not work at all. Do you guys have any idea what I might be doing wrong? My Event Listener Code is attached:

var stopButtonEl = document.getElementById("StopButton");
stopButtonEl.addEventListener("click",clearTDLoop);

Sry for the prior confusion, where my code example stated "StartButton" as the button ID, I copied the wrong ID, the problem persists..

Upvotes: 0

Views: 252

Answers (2)

Mohammad Usman
Mohammad Usman

Reputation: 39322

I've set an example code for you, please check it:

var tdLoop;
var counter = 0;

var startButton = document.getElementById('startButton');
startButton.addEventListener('click', startTDLoop, false);

var stopButton = document.getElementById('stopButton');
stopButton.addEventListener('click', clearTDLoop, false);

var result = document.getElementById('result');

function startTDLoop() {
  tdLoop = setInterval(updateValue, 1000);
}

function updateValue() {
  counter++;
  result.innerHTML = counter;
}

function clearTDLoop() {
  counter = 0;
  clearTimeout(tdLoop);
}
#result {
  padding: 15px 0 0;
}
<input type="button" class ="anhalteButton" id="startButton" value="Start"/>
<input type="button" class ="anhalteButton" id="stopButton" value="Stop"/>

<div id="result"></div>

Upvotes: 0

Maloric
Maloric

Reputation: 5615

It looks like you have the wrong ID for your event listener:

var startButtonEl = document.getElementById("StartButton");
startButtonEl.addEventListener("click",clearTDLoop);

Should be:

var stopButtonEl = document.getElementById("StopButton");
stopButtonEl.addEventListener("click",clearTDLoop);

Upvotes: 2

Related Questions