dSquared
dSquared

Reputation: 9825

Using jQuery or JavaScript to Add Attribute to Anchors After DOM Already Loaded

I have an application that requires the "ontouchstart" attribute to be added to each and every anchor in order to have the anchor:active CSS state to work on iOS devices.

Trouble is that the entire application loads content via AJAX after the DOM has already loaded, which means any $(selector).attr('ontouchstart','') call will only work on the initial screen, not content added later via AJAX.

Because each screen is being loaded by separate functions (in some cases being constructed by the function itself) I would like to find a solution that allows a single jQuery or JavaScript call that applies to all anchors, even those added after the DOM is loaded rather than going through each and every function and adding in the call individually (there are hundreds of them).

Is this even possible? Any help would be greatly appreciated.

Upvotes: 2

Views: 1220

Answers (3)

Clive
Clive

Reputation: 36955

You could try the DOMNodeInserted event:

$(document).bind('DOMNodeInserted', function(event) {
  if (event.target.nodeName == 'A') {
    $(event.target).attr('ontouchstart','');
  }
});

The event itself will fire when any type of node is added to the DOM, the code just tests the node name (tag) and adds the attribute.

Upvotes: 2

Pono
Pono

Reputation: 11786

live() and delegate() events are what you're looking for.

Upvotes: 1

Justin Lucas
Justin Lucas

Reputation: 2321

Try using the live or delegate event listeners. These both work with DOM elements added after the onload event.

Upvotes: 2

Related Questions