Detect External and Internal Links in a Web Page using jQuery – Expression Web
Posted by: Minal Agarwal
in Category Expression Web
Abstract: In this article, I will show you how to use jQuery to detect External and Internal Links in a HTML Web Page created using Expression Web.
In this article, I will show you how to use jQuery to detect External and Internal Links in a HTML Web Page created using Expression Web. Once again, I would like to mention Suprotim's eBook ’51 Recipes using jQuery and ASP.NET Controls’ which has been very helpful and helped me learn how to use jQuery in my ASP.NET web pages.
Sometime back, I had written on Using jQuery to Open External Links in a New Window - Expression Web and Using jQuery UI Datepicker in a Web Page - Expression Web. In this article, we will adopt a different approach of identifying external links by using the jQuery filter function
Launch Expression Web and create a new HTML Page (File > New or click on the New Document icon on Standard toolbar and choose HTML). Add the jQuery library CDN link in the <head> element of the page.
Now a link has various states (visited, hover, active etc). We can define CSS pseudo class selectors based on the state of the link. However for simplicity sake, let's just define one common css, as shown below:
Now add a couple of external as well as internal hyperlinks to the page. For this example, all the url’s beginning with https://www.dotnetcurry.com will be internal hyperlinks
It’s now time to add some jQuery code to detect external and internal links on the page. Add the following jQuery code in the <head> tag
In the code show above, we are using this.href.match(/^mailto\:/) so that we do not select any mailto: links. We are also comparing the location.hostname (in our case dotnetcurry) against the link's hostname using this.hostname != location.hostname. This code is wrapped inside the jQuery filter function which returns only those elements which pass the code inside the function, in our case, all links that did not match the hostname property of the site. We finally take this group of matched elements and apply the CSS class (.external) we created above, using the jQuery addClass()
The output is as shown below:
As you can observe, all external links are red in color with a dotted border. You can see a Live Demo over here
You can also download the entire source code over here.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce the pre-order of The Absolutely Awesome Book on C# and .NET. This is a concise technical eBook and will be available in PDF, ePub, and mobi.
Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core. Use these concepts in your next .NET Project or to crack your next .NET Interview.
Click here to Pre-Order this eBook at a Discounted Price!