Duane Boudreau
Duane Boudreau

Reputation: 130

jQuery - How do I add target="_blank" to external links in generated text

I need to add target="_blank" to all external links on my site normally I would use:

$("a[href^=http]").each(function(){
    if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
        });
    }
});

Unfortunately the links I need to check for are inside a div with the id of messageArea, and since they are generated via an ajax call, they arent getting picked up.

I could use c# regex functions and rewrite the content or add the target="_blank" but I would rather leave the content in its orginal state.

Any suggestions?


Using lucuma's suggestion the solution is:

$.getJSON(
   "ajax/GetMessage.aspx?message=" + msgID,
   function (msgs) {
       $("div#messageArea").html(msgs.responseText);
       $("div#messageArea a[href^=http]").each(function(){
           if(this.href.indexOf(location.hostname) == -1) {
               $(this).attr({
                   target: "_blank",
                   title: "Opens in a new window"
               });
           }
       });
    }
);

Upvotes: 0

Views: 2290

Answers (2)

nkt
nkt

Reputation: 75

<a href="http://google.com">google</a>

all is work Maybe you can show more code?

Upvotes: 0

lucuma
lucuma

Reputation: 18339

On the return from the ajax call add this code:

$("div#messageArea a[href^=http]").each(function(){
    if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
        });
    }
});

Upvotes: 1

Related Questions