Home > Net >  HTML Javascript buttons not responding while clicking
HTML Javascript buttons not responding while clicking

Time:05-03

Whenever I click the increment button , it doesn't show any output on the VS code terminal block.

It just shows the following output "if ($?) { start Firefox pEOPLEcOUNTERapp.htm }" just start the Firefox browser and when I click on increment button then --> no output

HTML CODE

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel = "stylesheet" href = "pEOPLEcOUNTERapp.css">
       
    </head>
    <body>
        <h1> People Entered</h1>
        <h2 id="count-el">0</h2>
        <script src="pEOPLEcOUNTERapp.js">
            // can write javascript
           
        
        </script>

        <button id="increment-btn" onclick="increment()">increment</button>
       
        
    </body>


</html>

    function increment(){ //javascript code
    console.log("THE BUTTON WAS clicked")
}

JavaScript Code:

function increment()
    console.log("THE BUTTON WAS clicked")
}

CodePudding user response:

Try it like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="increment-btn" onclick="increment()">increment</button>
  </body>
  <script>
    function increment() {
      console.log("THE BUTTON WAS clicked");
    }
  </script>
</html>

You have to add the script at the end of the document.

CodePudding user response:

This should work (no separate js file)

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel = "stylesheet" href = "pEOPLEcOUNTERapp.css">
    </head>
    <body>
        <h1> People Entered</h1>
        <h2 id="count-el">0</h2>
        <script>
            function increment(){ 
                console.log("THE BUTTON WAS clicked")
            }
        </script>

        <button id="increment-btn" onclick="increment()">increment</button>
       
    </body>
</html>

CodePudding user response:

It sounds like you want to update the count in that count-el element. If that's the case you do need to either defer the script or add your script call to just before the </body> tag to ensure the DOM has loaded, and your script can work on those elements.

This example removes the need for inline JS. It caches the elements, and then adds a listener to the button element. When that's clicked it calls the increment function which updates the text content of the count-el element.

const count = document.querySelector('#count-el');
const btn = document.querySelector('#increment-btn');

btn.addEventListener('click', increment, false);

function increment() {
  count.textContent = Number(count.textContent)   1;
}
<h1> People Entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn">increment</button>

  • Related