3

I have a list like the following:

<ul id="links">
    <li><a href="/example-url-1">Link 1</a></li>
    <li><a href="/example-url-2">Link 2</a></li>
    <li><a href="/example-url-3">Link 3</a></li>
</ul>

I'm adding a target attribute to each link using jQuery, because I don't want to alter the server-side HTML output; it's used in many other places and this is the only instance where the links should have this attribute.

$('#links a').attr('target', '_top');

The problem is that new links are dynamically appended to this list client-side, also using jQuery; when they are, they obviously lack the target attribute, so I end up with this sort of thing:

<ul id="links">
    <li><a href="/example-url-1" target="_top">Link 1</a></li>
    <li><a href="/example-url-2" target="_top">Link 2</a></li>
    <li><a href="/example-url-3" target="_top">Link 3</a></li>
    <li><a href="/example-url-4">Link 4</a></li>
</ul>

I cannot alter the jQuery script which is appending the links in order to include the attribute, so my question is this: I know I can use live() to automatically set up event handlers for dynamically generated elements, but is there a way of automatically adding attributes to any new elements added?

Mark Bell
  • 28,985
  • 26
  • 118
  • 145

4 Answers4

5

I don't think there's any way to do what you're asking. But you can use live to accomplish the same thing:

$('#links a').live("click", function(e) {
   $(this).attr('target', '_top');
});
Dave
  • 4,375
  • 3
  • 24
  • 30
  • I actually thought about doing exactly this; for some reason I got it into my head that it wouldn't work, because the click would have already happened before the attribute was assigned, which is complete nonsense... time to go home for the day, I think! – Mark Bell Jul 11 '11 at 15:52
1

If you're not averse to plugins, you might take a look at livequery, which will accomplish what you want.

Here's an example:

$("#links a").livequery(function () {
    $(this).prop("target", "_top");
}); 

http://jsfiddle.net/vRF3G/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
1

You might want to look into jQuery's special event system. It allows you to create custom special events that get triggered when certain conditions are met.

Here's another SO thread with a "onContentChange" event: Create a jQuery special event for content changed

And here's another article on jQuery Custom Special Events: http://benalman.com/news/2010/03/jquery-special-events/

Community
  • 1
  • 1
Alex Heyd
  • 1,323
  • 1
  • 10
  • 17
0

This is a terrible solution:

$("#links a").live("mouseover", function() { $(this).attr("target","_top"); });

Can't click on it without mousing over it, the target attribute is set before it is needed.

nwellcome
  • 2,279
  • 15
  • 23