I want to call my function in javascript when i click the button in html
I want to start the stopwatch as soon as I click the button.
Already thank you for your help?
I already saw some questions with similar topics but they couldnt help me.
function StopWatch(){
let isStart = false;
let startcount = 0;
let stocount = 0;
let durationcount= 0;
let preDuration = 0;
<button class="starttimer" onclick="doFunction(stopwatch)">
start timer
</button>
I tried to link the stopwatch function with the button div as shown below. I expected, that it would be linked with each other and the stopwatch function would start and the stopwatch would start as soon as I start the timer.
button onclick="doFunction(stopwatch)
3
Answers
//edit
\edit I missed this one.
Here’s a corrected inline version that you attempted. The function name must be the
onclick
value, and it must be used with()
so that the function is called.(Note: JavaScript functions are generally in camelcase starting with a lowercase letter.)
However! With modern JavaScript we like to separate our HTML markup and JavaScript. And to do this we:
Select the element in the markup with
querySelector
(here I’m picking up the element using its class name)Add a listener to the button with
addEventListener
which calls an event handler (ie your function) when fired.Oh, and maybe rename your function to something that represents the function it performs (I’ve changed it from
Stopwatch
tostartTimer
).You need to use the function name in your onclick call:
As long as the function is in a script tag accessible by your button, the function will be hit.