Note that there are some explanatory texts on larger screens.

plurals
  1. POonClick / onclick does not seem to be working as expected in HTML5 / JavaScript
    primarykey
    data
    text
    <p>I'm trying to do something very simple - call a function when a button is clicked. I've looked at several examples online, such as W3Schools and (I believe) I am using onclick / onClick correctly it does not seem to be functioning. I have tried several different methods - I'm really not sure what I'm doing wrong. </p> <p><strong>Method 1</strong></p> <p>HTML </p> <pre><code>&lt;button id="buttonAdd" onclick="add()"&gt;Add&lt;/button&gt; </code></pre> <p>JavaScript</p> <pre><code>function add() { console.log("Test"); } </code></pre> <p>Result:</p> <blockquote> <p>Test</p> </blockquote> <p>When the button is clicked this flashes up in the console.log faster than I can easily see and then disappears. </p> <p><strong>Method 2</strong> </p> <p>HTML</p> <pre><code>&lt;button id="add"&gt;Add&lt;/button&gt; </code></pre> <p>JavaScript</p> <pre><code>window.onload = function() { document.getElementById("add").onclick = add; } function add() { console.log("Test"); } </code></pre> <p>Result</p> <blockquote> <p>Test</p> </blockquote> <p>When the button is clicked this flashes up in the console.log faster than I can easily see and then disappears. </p> <p><strong>Method 3</strong> </p> <p>HTML</p> <pre><code>&lt;button id="add"&gt;Add&lt;/button&gt; </code></pre> <p>JavaScript</p> <pre><code>window.onload = function() { document.getElementById("add").onclick = add(); } function add() { console.log("Test"); } </code></pre> <p>Result</p> <blockquote> <p>Test</p> </blockquote> <p>This appears in the console log and remains there, without the button having been clicked.</p> <p><strong>Issue</strong> </p> <p>I'm generally feeling confused. From what I can tell I am doing what is suggested by examples (the different methods I have tried reflect differences in examples). </p> <p>Thanks. </p> <p><strong>Edit</strong></p> <p>So it seems the issue is the console.log flashing up almost faster than I can see... Does anyone have any idea why this might be? It seems like the page is refreshing itself, but I have no idea why this would be... </p> <p><strong>Answer</strong> </p> <p>The button was in a form which caused the page to refresh when it was clicked. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload