Reputation: 93611
I have a jQuery plugin that overrides link behavior, to allow Ajax loading of page content. Simple enough with a delegated event like $(document).on('click','a', function(){});
.
but I only want it to apply to links that are not like these ones (Ajax loading is not applicable to them, so links like these need to behave normally):
target="_blank" // New browser window
target="_self" // Force replacement of current window (specific to my plugins)
href="#..." // Bookmark link (page is already loaded).
href="afs://..." // AFS file access.
href="cid://..." // Content identifiers for MIME body part.
href="file://..." // Specifies the address of a file from the locally accessible drive.
href="ftp://..." // Uses Internet File Transfer Protocol (FTP) to retrieve a file.
href="http://..." // The most commonly used access method.
href="https://..." // Provide some level of security of transmission
href="mailto://..." // Opens an email program.
href="mid://..." // The message identifier for email.
href="news://..." // Usenet newsgroup.
href="x-exec://..." // Executable program.
href="http://AnythingNotHere.com" // External links
$(document).on('click', 'a:not([target="_blank"])', function(){
var $this = $(this);
if ('some additional check of href'){
// Do ajax load and stop default behaviour
return false;
}
// allow link to work normally
});
Is there a way to easily detect all "local links" that would only navigate within the current website? excluding all the variations mentioned above.
Note: This is for an MVC 5 Razor website, so absolute site URLs are unlikely to occur.
Upvotes: 3
Views: 1340
Reputation: 92983
I might use the selector:
$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"])')
http://jsfiddle.net/mblase75/Pavg2/
Note that mailto:
is correct, not mailto://
as in your original question.
In the interest of thoroughness, the following will also catch internal links that use absolute URLs (http://the-domain-you-are-on-now.com/whatever.html
):
$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"]),a[href^="'+location.protocol+'//'+location.hostname+'"]')
http://jsfiddle.net/mblase75/Pavg2/4/
Upvotes: 4
Reputation: 159
I don't know why you voted down my last answer but on reference url you will find exact condition
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)){
//do stuff when it an external link
}
else{
// do stuff when it's internal link
}
Here is reference http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/
Upvotes: 3