monkeydeus
monkeydeus

Reputation: 395

JS event handler with custom html attributes

I am revisiting/learning/unlearning what I thought I knew about custom attributes. Most of the information I've found here is a discussion of whether they are 'acceptable' or not, but I haven't seen a discussion of my question:

If you have a collection of elements to be handled by a common event handler (say a collection of thumbnail versions of pictures, or product detail thumbnails that when clicked would populate a main product details panel), what would be the preferred method of doing this without using custom attributes, if that is not a valid approach?

Say you wanted an onclick handler that would pass a parameter to a web service, and you were storing that parameter in an attribute "productDetail", e.g:

<img src="couchthumb.jpg" productDetail="couch_95" />

And you wanted to do this for each of the thumbnails on your couches page.

What is the better approach if not to do it this way?

Upvotes: 0

Views: 137

Answers (1)

Pointy
Pointy

Reputation: 413757

In HTML 5, you can use "data-" attributes:

<img src='couchthumb.jpg' data-product-detail='couch_95'>

All attributes of that form are valid attributes (in HTML 5).

Another approach (if you're concerned about doing things "right", whatever that means to you) is to use the "class" attribute for things like that:

<img src='couchthumb.jpg' class='productDetail:couch_95'>

Your code would have to pull the value out with a regex or something.

Upvotes: 1

Related Questions