I'm Geeker
I'm Geeker

Reputation: 4637

How to access the canvas using jquery?

I'm not able to access the canvas id using jquery.

I added the jQuery Library. But I'm not able to get an alert when I click the canvas id.

But javascript is working fine.

    <script>
    $(document).ready(function(){
    $('#sq').click(function(){
    alert('test');
    });
    });
    </script>
    <canvas id="example" width="260" height="200">
        <h2>Shapes</h2>
      <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the 
      <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>. 
      Partially overlaying the circle is a green 
      <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();" id="sq">square</a> 
      and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>, 
      both of which are semi-opaque, so the full circle can be seen underneath.</p>
    </canvas>​

Upvotes: 2

Views: 682

Answers (3)

tBX
tBX

Reputation: 184

Take the html elements out of the canvas and change $('#sq').click(function(){ to $('#example').click(function(){

Look at this: http://jsfiddle.net/Zprb4/

Upvotes: 1

iMoses
iMoses

Reputation: 4348

You are not suppose to put html elements inside the canvas tag. The idea of the canvas is to draw on it using code (a.k.a. javascript). What you are doing isn't gonna work (or more likely will be seen only if the browser doesn't support canvas - which means very very old browsers) :)

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Everything you've put inside your canvas element is fallback content : It won't be used in a modern browser so you can't access it and you certainly can't click on it.

The correct use of a canvas in a modern browser is to draw onto it using its context.

From the MDN :

The < canvas > element is an HTML element which can be used to draw graphics via scripting (usually JavaScript). For example, it can be used to draw graphs, make photo compositions, create animations or even do real-time video processing.

If you want to catch clicks on the canvas, do

$('#example').click(function(){ // <-- use the id of the canvas
    alert('test');
});

Upvotes: 3

Related Questions