The most common way to add link in new tab is via adding “_blank” to the hyperlinks, but it is too annoying if in case you keep adding manually more and more such links site-wide. We can open Hyperlinks in a new window using jQuery and customize hyperlinks with CSS to stand them out.
//open all hyperlinks in a new window using jQuery
$(this).attr('href', newHref).attr("target", "_blank");
Opening External Links in New Tab
This code checks for the domain/keyword, and then adds a blank-target attribute to any non-matches. You can change the
entranceking.com to match your own domain. It’s a handy little snippet that can make targeting external links super easy. You could modify the code a bit to add a class for custom link styles or whatever floats your boat.
If you don’t already have jQuery need a local copy of it or use Google’s hosted library CDN (Content Delivery Network) for jQuery.
There are two types of jQuery version Production and Development version of jQuery.
- Production version – This version is for Live Website. It is already Minified and compressed.
- Development version – This version is purely for Testing and Development purpose. Code is uncompressed and in readable form.
You can download both the version from jQuery.com.
Why to host jQuery over Google CDN?
Many many users would have downloaded jQuery from Google while browsing some another site. As a result, it will be loaded from their cache and not from your site. You end up saving a hit and this leads to faster loading time. Generally most CDN ensure that once user requests for a file from it, it will be served from the server closest to them which leads to faster loading time.