Jimmy Z
Jimmy Z

Reputation: 743

Unobtrusive JavaScript - Safe Attributes?

I'm working on separating JavaScript code from my HTML. I currently have code that looks like this:

<div onclick="return do_something_with('100566');" class="clickable">Click Me!</div>

I'd like to swap the onclick to an attribute containing just the parameter I'm passing to the method.

I'm using jQuery for this with the following type of code:

var $j = jQuery;
$j(function(){
    $j('.clickable').live('click',function(){
        param = $j(this).attr('attribute_name');
        do_something(param);
    });
});

What attribute can I use for 'attribute_name' that would be safe for communicating this parameter value? I know I can use id, but I would have already defined an element with the same id in a different place in the DOM.

Any suggestions?

Upvotes: 2

Views: 646

Answers (6)

cdmckay
cdmckay

Reputation: 32240

I usually add a meaningful prefix like Client-100566 and then access it using this code:

var param = $(this).attr("id").split("-")[1];

Edit: Removed suggestion for invalid all-number id token.

Upvotes: 4

Noon Silk
Noon Silk

Reputation: 55082

You can just make up any attribute name.

<div onclick="foo();" silkyvalue="12938">hello</div>

I'd generally go with some naming format though, like 'my_somethingID'.

Upvotes: 0

Colin
Colin

Reputation: 2502

Couldn't you use the rel tag on an a inside the div? It allows for 1 parameter or n parameters to be passed through to doSomething.

<div>
  <a class="clickable" rel="param1 param2 param3">Click Me!</a>
</div>

So now when param is sent to doSomething it is a space separated list which param.indexOf("param1") can be used to check what parameters have been sent through?

Upvotes: 1

gnarf
gnarf

Reputation: 106332

I often find myself either using id for things that will be unique, or sticking in a hidden <span> with the data.

Upvotes: 2

Pat
Pat

Reputation: 25675

You could use the class or title attributes as space separated lists of parameters. The downside to the title is that it would show as a popup when your element was hovered:

<div class="clickable param1 param2 param3">

or

<div class="clickable" title="param1 param2 param3">

Here's a list of other attributes you might consider too.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190945

Why don't you make these a tags? There are several sites that use the anchor (the #someThing) part or use the rel attribute.

Upvotes: 0

Related Questions