Mipod
Mipod

Reputation: 135

Add target on elements added dynamically

I'm a novice in jQuery and I got stuck whit a problem for a while now. I am trying to discover all the links to an external page and add a target="_blank" attribute to them. So far I have created the following script:

$(document).on('load',function() {
$('a').each(function () {
    if (location.hostname !== this.hostname) {
        $(this).attr('target', '_blank');
    }
});
});

This works fine on the elements that are loaded on the page in the first instance, but when new elements are added dynamically it doesn't fire again to add the target attribute. I have tried to change the "ready" function to "on('load')" but to no success.

Any help is highly appreciated and I am grateful for the people who take a second to answer silly questions like this.

Edit: I created and infinite scroll script that loads more elements through an AJAX call. This elements contain "a" tags and I would like the script to run again for them.

Upvotes: 0

Views: 484

Answers (3)

James
James

Reputation: 22247

I would wrap your link-changing code in a function which you can call a) onload and b) when your content changes.

$(document).ready(function() {
  linkChanger();
});

function linkChanger() {
  $('a').each(function () {
      if (location.hostname !== this.hostname) {
          $(this).attr('target', '_blank');
      }
  });
}

then if you add content/links later, you can call linkChanger() to check/convert your page again:

$('#something').click(function () {
  // code that gets more content, if async provide a callback that calls linkChanger()
  linkChanger();
});

Upvotes: 1

chris lawson
chris lawson

Reputation: 21

It is possible that you are targeting the A links before the new elements have been created, Try running the code in a setTimeout function. for example

$(document).on('load',function() {

setTimeout(function(){ $('a').each(function () { if (location.hostname !== this.hostname) { $(this).attr('target', '_blank');
} }); }, 5000);

});

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113455

You have to trigger that function whenever you add new elements. Because you is the best person to know when new links are being added, so you have to set up the scripts in that way.

function setTargetBlank () {
  $('a').each(function () {
    if (location.hostname !== this.hostname) {
      $(this).attr('target', '_blank');
    }
  });
}

// On load
$(function () {
  setTargetBlank();
  loadSomeContent(function () {
    // And after it is loaded, trigger again the function
    setTargetBlank();
  });
});

If you cannot control these, you can simply set up a timer which will always trigger that function every few seconds:

 // This is not really good for performance, but it will work
 // It will trigger the function every 3 seconds
 setInterval(setTargetBlank, 3 * 1000);

Upvotes: 1

Related Questions