darklord
darklord

Reputation: 5167

HTML5 how to get the id of the object that is clicked on?

I have a list of canvas like this:

<div id="lists" style="position:absolute">
        <ul>
            <li>
                <canvas id="product1" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product2" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product3" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product4" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product5" class="product" width="1200" height="360"></canvas>
            </li>
        </ul>
    </div>

I want to write a event listeners for all the five canvass:

$(".product").mousedown(function(e) {

}

I want to know which canvas the user clicked on in the event handler. Is there a way to know that? If I write five event handler for the five canvases, the code will be too ugly.

Upvotes: 0

Views: 347

Answers (1)

Haneev
Haneev

Reputation: 775

The answer is in the event object and the context of which it is called, those are parsed with the callback function. You can look at $(this) or http://api.jquery.com/event.target/.

$(".product").mousedown(function(e) {
    alert($(this).attr('id'));
});

Will give you the ID

Upvotes: 5

Related Questions