jQuery Open Link with Class in New Window

Glenn Blog 0 Comments

Sometimes out of the box code doesn’t open links in new windows / in window “_blank” and in these instances this small jQuery snippet will come to the rescue:-


<script>
jQuery(document).ready(function($) {
$('a.external-url').live('click', function(){jQuery
  $(this).attr('target','_blank');
});
  });
</script>

So simply add the class “external-url” to your link and it will open in a new window.


<a href="https://slickmedia.co.uk/" class="external-url" title="wordpress developers">Slick Media Wordpress Developers</a>

Working: Slick Media WordPress Developers

I find this useful for WordPress elements that you can add custom classes to.

If you want to achieve the same thing by automatically using the link’s “rel” attribute then you could also use:-


$('A[rel="external"]')
.click( function() {
window.open( $(this).attr('href') );
return false;
});

About the Author
jQuery Open Link with Class in New Window jQuery Open Link with Class in New Window 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

Your email address will not be published. Required fields are marked *