Change href of external links

View: New views
20 Messages — Rating Filter:   Alert me  
< Prev | 1 - 2 | Next >

Change href of external links

by agent2026 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi all,

New to jQuery, and I'm trying to use it to set my external links to open a new window without using any attributes to  mark the external links.  I can do this with regular js, using a.href.match, but I can't get it to work with jQuery.  Tried various directions, but no go.

Sure I'll feel pretty stupid when this is answered, but here is my ugly, non-functioning code:

$(function(){
    if ($!("a").href.match("http://www.internal.com")) {
        $("a").click(
             function() {
                 window.open(this.href); return false;
                 console.log("external");
             };
        );
    };
});



Thanks for any help,
Adam

Re: Change href of external links

by Sam Collett :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 28/11/06, agent2026 <adamd@...> wrote:

>
> Hi all,
>
> New to jQuery, and I'm trying to use it to set my external links to open a
> new window without using any attributes to  mark the external links.  I can
> do this with regular js, using a.href.match, but I can't get it to work with
> jQuery.  Tried various directions, but no go.
>
> Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> non-functioning code:
>
> $(function(){
>     if ($!("a").href.match("http://www.internal.com")) {
>         $("a").click(
>              function() {
>                  window.open(this.href); return false;
>                  console.log("external");
>              };
>         );
>     };
> });
>
>
>
> Thanks for any help,
> Adam
> --

This may work (untested), grabs all anchors that don't begin with http
(internal links should be referred to using '../../foo.html' or
'/bar.jpg'):

$("a").not("[@href^=http]").click(
    function(){
        window.open(this.href);
        console.log('external');
        return false;
    }
)

$("a:not[@href^=http]") may also work.

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Jörn Zaefferer :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> > New to jQuery, and I'm trying to use it to set my external links to open
> a
> > new window without using any attributes to  mark the external links.  I
> can
> > do this with regular js, using a.href.match, but I can't get it to work
> with
> > jQuery.  Tried various directions, but no go.
> >
> > Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> > non-functioning code:
> >
> > $(function(){
> >     if ($!("a").href.match("http://www.internal.com")) {
> >         $("a").click(
> >              function() {
> >                  window.open(this.href); return false;
> >                  console.log("external");
> >              };
> >         );
> >     };
> > });
>
> This may work (untested), grabs all anchors that don't begin with http
> (internal links should be referred to using '../../foo.html' or
> '/bar.jpg'):
>
> $("a").not("[@href^=http]").click(
>     function(){
>         window.open(this.href);
>         console.log('external');
>         return false;
>     }
> )
>
> $("a:not[@href^=http]") may also work.

When testing, keep in mind that browsers behaviour with href attributes is quite inconsistent. While some return only the value as found in the markup, others add the domain and protocol.
--
Der GMX SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen!
Ideal für Modem und ISDN: http://www.gmx.net/de/go/smartsurfer

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Sam Collett :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 28/11/06, "Jörn Zaefferer" <Enchos@...> wrote:

> > > New to jQuery, and I'm trying to use it to set my external links to open
> > a
> > > new window without using any attributes to  mark the external links.  I
> > can
> > > do this with regular js, using a.href.match, but I can't get it to work
> > with
> > > jQuery.  Tried various directions, but no go.
> > >
> > > Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> > > non-functioning code:
> > >
> > > $(function(){
> > >     if ($!("a").href.match("http://www.internal.com")) {
> > >         $("a").click(
> > >              function() {
> > >                  window.open(this.href); return false;
> > >                  console.log("external");
> > >              };
> > >         );
> > >     };
> > > });
> >
> > This may work (untested), grabs all anchors that don't begin with http
> > (internal links should be referred to using '../../foo.html' or
> > '/bar.jpg'):
> >
> > $("a").not("[@href^=http]").click(
> >     function(){
> >         window.open(this.href);
> >         console.log('external');
> >         return false;
> >     }
> > )
> >
> > $("a:not[@href^=http]") may also work.
>
> When testing, keep in mind that browsers behaviour with href attributes is quite inconsistent. While some return only the value as found in the markup, others add the domain and protocol.
> --

So perhaps an additional check is needed, i.e. use location.hostname?

$("a").not("[@href^=http]").click(
    function(){
        if(this.href.indexOf(location.hostname) == -1) {
                window.open(this.href);
                console.log('external');
                return false;
        }
    }
)

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Paul McLanahan :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Actually, you have to check for href attribs that start with "http"
but then make sure that they're not "http://yourdomain.com" because IE
will translate relative links into absolute ones in the returned
string from aTagRef.href. I'd also make sure that they don't start
with "javascript:" and "mailto:".

On 11/28/06, Sam Collett <sam.collett@...> wrote:

> On 28/11/06, agent2026 <adamd@...> wrote:
> >
> > Hi all,
> >
> > New to jQuery, and I'm trying to use it to set my external links to open a
> > new window without using any attributes to  mark the external links.  I can
> > do this with regular js, using a.href.match, but I can't get it to work with
> > jQuery.  Tried various directions, but no go.
> >
> > Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> > non-functioning code:
> >
> > $(function(){
> >     if ($!("a").href.match("http://www.internal.com")) {
> >         $("a").click(
> >              function() {
> >                  window.open(this.href); return false;
> >                  console.log("external");
> >              };
> >         );
> >     };
> > });
> >
> >
> >
> > Thanks for any help,
> > Adam
> > --
>
> This may work (untested), grabs all anchors that don't begin with http
> (internal links should be referred to using '../../foo.html' or
> '/bar.jpg'):
>
> $("a").not("[@href^=http]").click(
>     function(){
>         window.open(this.href);
>         console.log('external');
>         return false;
>     }
> )
>
> $("a:not[@href^=http]") may also work.
>
> _______________________________________________
> jQuery mailing list
> discuss@...
> http://jquery.com/discuss/
>

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Paul McLanahan :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

For further clarification, here's some sample (untested mock up) code
that is a jQuery version of something I did a while back:

allowedDomains = ['mydomain.com','myotherdomain.net'];
$('a[@href^="http"]').each(function(){
        var isExt = true;
        for(var i=0;i<allowedDomains.length;i++){
                if(this.href.indexOf(allowedDomains[i])>-1){
                        isExt=false;
                        break;
                }
        }
        if(isExt){
                $(this).click(function(){
                        window.open(this.href);
                        return false;
                });
        }
});

That way you can set up whatever strings you want to allow to be
excluded in the allowedDomains array thus ensuring that the links you
find really are external to your site's domain(s).

On 11/28/06, Paul McLanahan <pmclanahan@...> wrote:

> Actually, you have to check for href attribs that start with "http"
> but then make sure that they're not "http://yourdomain.com" because IE
> will translate relative links into absolute ones in the returned
> string from aTagRef.href. I'd also make sure that they don't start
> with "javascript:" and "mailto:".
>
> On 11/28/06, Sam Collett <sam.collett@...> wrote:
> > On 28/11/06, agent2026 <adamd@...> wrote:
> > >
> > > Hi all,
> > >
> > > New to jQuery, and I'm trying to use it to set my external links to open a
> > > new window without using any attributes to  mark the external links.  I can
> > > do this with regular js, using a.href.match, but I can't get it to work with
> > > jQuery.  Tried various directions, but no go.
> > >
> > > Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> > > non-functioning code:
> > >
> > > $(function(){
> > >     if ($!("a").href.match("http://www.internal.com")) {
> > >         $("a").click(
> > >              function() {
> > >                  window.open(this.href); return false;
> > >                  console.log("external");
> > >              };
> > >         );
> > >     };
> > > });
> > >
> > >
> > >
> > > Thanks for any help,
> > > Adam
> > > --
> >
> > This may work (untested), grabs all anchors that don't begin with http
> > (internal links should be referred to using '../../foo.html' or
> > '/bar.jpg'):
> >
> > $("a").not("[@href^=http]").click(
> >     function(){
> >         window.open(this.href);
> >         console.log('external');
> >         return false;
> >     }
> > )
> >
> > $("a:not[@href^=http]") may also work.
> >
> > _______________________________________________
> > jQuery mailing list
> > discuss@...
> > http://jquery.com/discuss/
> >
>

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> When testing, keep in mind that browsers behaviour
> with href attributes is quite inconsistent. While some
> return only the value as found in the markup, others
> add the domain and protocol.

Right, IE usually adds the base href to relative URLs. I think this would
work in all browsers:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .bind("click", "!window.open(this.href)");

That's the short (and a hair slower) form of this:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .bind("click", function(){
       return !window.open(this.href);
   });

By applying the not (!) operator to window.open it returns false to stop the
default action only if the window opens; if a popup blocker intervenes,
window.open returns null and the click handler will return true to allow the
default action--following the link.

Theoretically, .not("[@href*='internal.com/']") could incorrectly match some
non-local URLs if  "internal.com/" was outside the domain name; it shouldn't
be in the query string because "/" should be encoded there. So it seems
pretty safe to use this.

Another approach would be to define a target attribute on the external links
and the browser will open them in a new tab or window:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .attr("target", "_blank");



_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by agent2026 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Thanks guys, excellent solutions and points.  I've gone with Dave's solution, as it allows some tag flexibility without adding much code.

One question: is it not possible to combine .not arguments?  Tried playing with the quotes, but it only seems to work if they are separated.

.not("[@href*='internal.com/']")
.not("[@class*='thickbox']")

vs

.not("[@href*='internal.com/']" || "[@class*='thickbox']")  // or some variation


Adam

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> One question: is it not possible to combine .not arguments?
> Tried playing with the quotes, but it only seems to work if
> they are separated.
>
> .not("[@href*='internal.com/']")
> .not("[@class*='thickbox']")

Even better, you could use the :not() selector to do the job all at once, I
forgot about it.

  $("a[@href=^http]:not([@href*='internal.com/']):not(.thickbox)")
     .bind("click", function(){ return !window.open(this.href); });

This is the way jQuery optimization usually goes. You start with 10 lines of
jQuery that would have been 20 lines of tedious DOM Javascript. By the time
you are done it's down to two or three lines and it couldn't get any shorter
unless it read your mind. :-)



_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by agent2026 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Lol, sweet.  Looking forward to the ESP version.

Small typo, in case anyone comes across this:
dave.methvin wrote:
  $("a[@href=^http]:not([@href*='internal.com/']):not(.thickbox)")
     .bind("click", function(){ return !window.open(this.href); });
Should be [@href^=http], not [@href=^http]


Thanks,
Adam

Re: Change href of external links

by Klaus Hartl-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Dave Methvin schrieb:
"You start with 10 lines of jQuery that would have been 20 lines of
tedious DOM Javascript. By the time you are done it's down to two or
three lines and it couldn't get any shorter unless it read your mind."

Dave, ha, that is a great quote. It belongs to the homepage!



-- Klaus

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Felix Geisendörfer :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Dave Methvin schrieb:
"You start with 10 lines of jQuery that would have been 20 lines of 
tedious DOM Javascript. By the time you are done it's down to two or 
three lines and it couldn't get any shorter unless it read your mind."
Dave, ha, that is a great quote. It belongs to the homepage!

I agree. And it's very true. When first using jQuery I was able to cut down my custom code in half instantly. And that was before I really knew what I was doing - using the library was very natural right from the beginning. Now the entire code could probably fit on small napkin ; ).

-- Felix


Klaus Hartl wrote:
Dave Methvin schrieb:
"You start with 10 lines of jQuery that would have been 20 lines of 
tedious DOM Javascript. By the time you are done it's down to two or 
three lines and it couldn't get any shorter unless it read your mind."

Dave, ha, that is a great quote. It belongs to the homepage!



-- Klaus

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

  

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by agent2026 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I was just looking at this again, and wondered how I could make it work with a string of links to not be external.  For example using a for loop to go through var intLink = link1, link2, link3, etc.  Just not sure how to go about getting the loop in there.

  $("a[@href^=http]:not([@href*='"+intLink+"']):not(.thickbox)")
    .bind("click", function(){ return !window.open(this.href); });

Adam


dave.methvin wrote:
Even better, you could use the :not() selector to do the job all at once, I
forgot about it.

  $("a[@href=^http]:not([@href*='internal.com/']):not(.thickbox)")
     .bind("click", function(){ return !window.open(this.href); });

This is the way jQuery optimization usually goes. You start with 10 lines of
jQuery that would have been 20 lines of tedious DOM Javascript. By the time
you are done it's down to two or three lines and it couldn't get any shorter
unless it read your mind. :-)

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> I was just looking at this again, and wondered how I could
> make it work with a string of links to not be external.  For
> example using a for loop to go through var intLink = link1,
> link2, link3, etc.
>
>  $("a[@href^=http]:not([@href*='"+intLink+"']):not(.thickbox)")
>    .bind("click", function(){ return !window.open(this.href); });

You could do it by creating a custom selector that joined a bunch of :not()
clauses:

 var notthese = ["http://test.com", "http://toast.com"];
 var sel = "a[@href^=http]:not(.thickbox)";
 for ( var i=0; i < notthese.length; i++ )
     sel += ":not(@href*="+notthese[i]+")";
 $(sel).bind("click", function(){ return !window.open(this.href); });

Or you could filter them manually:

 $("a[@href^=http]:not(.thickbox)").each(function(){
    for ( var i=0; i < notthese.length; i++ )
        if ( this.href == notthese[i] ) return;
    $(this).bind("click", function(){ return !window.open(this.href); });
 });

It would be nice if there was a $().grep() to filter the elements:

 $("a[@href^=http]:not(.thickbox)").grep(function(){
    for ( var i=0; i < notthese.length; i++ )
        if ( this.href == notthese[i] ) return false;
    return true;
  }).bind("click", function(){ return !window.open(this.href); });

But that doesn't exist. There's a jQuery.grep but it can't be used in a
chain.


_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Jonathan Sharp :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 12/14/06, Dave Methvin <dave.methvin@...> wrote:
*SNIP*
It would be nice if there was a $().grep() to filter the elements:

$("a[@href^=http]:not(.thickbox)").grep(function(){
    for ( var i=0; i < notthese.length; i++ )
        if ( this.href == notthese[i] ) return false;
    return true;
  }).bind("click", function(){ return !window.open(this.href); });

But that doesn't exist. There's a jQuery.grep but it can't be used in a
chain.

I looked at 1.0.3 source and filter() accepts a function and it appears that if that function returns true the element is included otherwise it returns false. The function you define takes two args: element, and i with i being the position in the current list or stack.

(Untested)
$("a[@href^=http]:not(.thickbox)").filter(function(el){
    for ( var i=0; i < notthese.length; i++ )
    if ( el.href == notthese[i] ) return false;
        return true;
    }).bind("click", function(){ return !window.open(this.href); });

Cheers,
-js



_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> I looked at 1.0.3 source and filter() accepts a function and it
> appears that if that function returns true the element is included
> otherwise it returns false.
 
Thanks for pointing that out Jonathan, I was almost certain there was one but I thought it was .grep() and the docs don't mention that variant of .filter(). 

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by Jonathan Sharp :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 12/14/06, Dave Methvin <dave.methvin@...> wrote:
> I looked at 1.0.3 source and filter() accepts a function and it
> appears that if that function returns true the element is included
> otherwise it returns false.
 
Thanks for pointing that out Jonathan, I was almost certain there was one but I thought it was .grep() and the docs don't mention that variant of .filter(). 

Ultimately filter utilizes .grep() but like you said grep was destructive. And you're right that the docs don't mention the acceptance of a function... here here for open source!

Cheers,
-js

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Change href of external links

by wycats :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.
If that was the case, jQuery("#main a").filter(function() { return false; }) would return nothing. But it doesn't. It returns the original group of elements. At least for me.

-- Yehuda

On 12/14/06, Dave Methvin <