skip to Main Content

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


  1. Chosen as BEST ANSWER

    //edit

    <button class="starttimer" onclick="doFunction(stopwatch)">

    \edit I missed this one.


  2. 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.)

    function stopwatch() {
      console.log('function called');
    }
    <button class="starttimer" onclick="stopwatch()">
      Start timer
    </button>

    However! With modern JavaScript we like to separate our HTML markup and JavaScript. And to do this we:

    1. Select the element in the markup with querySelector (here I’m picking up the element using its class name)

    2. Add a listener to the button with addEventListener which calls an event handler (ie your function) when fired.

    3. Oh, and maybe rename your function to something that represents the function it performs (I’ve changed it from Stopwatch to startTimer).

    const button = document.querySelector('.starttimer');
    button.addEventListener('click', startTimer);
    
    function startTimer() {
      console.log('function called');
    }
    <button class="starttimer">
      Start timer
    </button>
    Login or Signup to reply.
  3. You need to use the function name in your onclick call:

    onclick="StopWatch()"
    

    As long as the function is in a script tag accessible by your button, the function will be hit.

    <script>
        function StopWatch() {
            ... your code
        }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search