views:

282

answers:

2

I have any number of anchor links on a page that need to execute the same block of JavaScript code on click, and that code needs to be associated with one value. There are several of these on each page. I usually use a hidden input to store the value in a one-to-one relationship, but what is the best way to associate several links placed throughout a page with a value?

For example, think of a group of links that reference a product by ID, and all show the same dynamic layer for the product. Now there might be a multiple groups of links for a bunch of products. How do I draw those associations? I'm using Mootools and bind events by class, so I don't want a bunch of inline event function calls that pass arguments.

A: 

Do you want to set the values in your html code? Otherwise, you can dynamically add the values to the dom nodes themselves.

If you want to set them in the html, use a custom attribute if you don't care for standard compliance. If you do care, encode the values as class names or use the lang-attribute and prefix your data with 'x-' so you stay compliant to RFC 1766.

Christoph
I've seen this approach before, but doesn't metadata in the class name require the use of a custom namespace?
hal10001
+1  A: 

If your already using Mootools, a good way to do this is using the element's data storage.

window.addEvent('domready', function() {
  $$('a.classname').each(function(el) {
    el.store('productID', /*get this however you want*/);

    el.addEvent('click', function(e) {
      var productID = el.retrieve('productID');
    }
  }
}

And here's one method for getting the productID's (assuming you have control over URL formatting):

<a href='ViewProduct.php?ProductID=7#pid:7'>link</a>

//in your js (above)
var pid = el.get('href').split('#')[1].split(':')[1];
el.store('productID', pid);
tj111
I used a variation of this, but this was a very good approach to take.
hal10001