Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should be using 'click' and not 'onclick'. "on" is only used when setting it as a property (e.g., canvas.onclick = clickReporter).</p> <pre><code>canvas.addEventListener('click', clickReporter, false); </code></pre> <p><strong>UPDATE</strong></p> <p>More details on click vs. onclick.</p> <p>There are three ways to attach an event listener to an object in JavaScript:</p> <ol> <li><p>Through <em>element</em>.addEventListener. When you use this, you specify the event name you want to set. For example, 'click', or 'mouseover', or 'touchstart'. In this case, you're specifying the event's actual name. This is useful because you can add more than one listener to an event.</p> <pre><code>canvas.addEventListener('click', clickReporter, false); canvas.addEventListener('click', otherClickReporter, false); // Both clickReporter and otherClickReporter will be called on a click event. </code></pre></li> <li><p>Through <em>element</em>.onsomeevent (onclick, onmouseover, ontouchstart). This is an older convention which is fully standard and supported in HTML5. This is a very easy way to set the event listener but it has its drawbacks. Only one event listener can be set at a time with this method:</p> <pre><code>canvas.onclick = clickReporter; canvas.onclick = otherClickReporter; // Only otherClickReporter will be called on a click event. </code></pre></li> <li><p>Through the HTML itself. This is where all the conventions started. You can define an event directly in the HTML very much like the previous example:</p> <pre><code>&lt;canvas onclick="clickReporter()"&gt;&lt;/canvas&gt; </code></pre> <p>This is the same as the following, assuming that clickReporter gets attached to the window object.</p> <pre><code>&lt;canvas&gt;&lt;/canvas&gt; &lt;script&gt; canvasWeJustCreated.onclick = function() {clickReporter();} &lt;/script&gt; </code></pre></li> </ol> <p>Arguably the way you are doing it is the best way. There will certainly be cases where you want to use the other methods, like when generating a page on the server or trying to temporarily suppress scrolling on an iPhone, but for most applications, addEventListener is best.</p>
 

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