Accessibility new window warning

I came across a great plugin that adds a warning that a link goes to an external website.

You can see an example below with a link to the original plugin I forked the code from.

Plugin: Accessibility New Window Warnings

I wanted a simple way to add the functionality from the plugin, but as a code snippet so I didn’t need to add another plugin. The code below is a forked/modified version of the plugin with only the required code.

function tct_accessibilty_window_css() { ?> <style> .tct-external-link-icon:before { content: url("data:image/svg+xml,"); width: 15px; margin-left: 3px; display: inline-block; } </style> <?php } add_action('wp_head', 'tct_accessibilty_window_css');

The long URL encoded content is a font awesome external icon.

function tct_accessibilty_window_js() { ?> <script> (function ($) { "use strict"; $(window).on('load',function () { /** * Accessible _blank link tooltip */ var tct_link_tooltip = $('<div/>').css({ position: 'absolute', background: 'white', border: '1px solid black', padding: '5px 10px', zIndex: 999, display: 'none' }).appendTo('body'); /** * loop through each link with a target of _blank */ $("a[target=_blank]").each(function(){ // add icon to link if($(':header',this).length){ $(':header',this).append(' <i class="tct-external-link-icon" aria-hidden="true"></i>'); }else{ $(this).append(' <i class="tct-external-link-icon" aria-hidden="true"></i>'); } // add aria-label to link $(this).attr("aria-label", $(this).text()+", opens a new window"); // position and show link_tooltip on hover $(this).mousemove(function(e){ tct_link_tooltip.css({ top: e.pageY + 10 + 'px', left: e.pageX + 10 + 'px' }); }) .hover(function(){'opens a new window'); }, function(){ tct_link_tooltip.hide(); }); // position and show link_tooltip on focus $(this).on({ focusin: function () { var position = $(this).position(); tct_link_tooltip.css({ top: + $(this).outerHeight() + 'px', left: position.left + 'px' });'opens a new window'); }, focusout: function () { tct_link_tooltip.hide(); } }); }); }); })(jQuery); </script> <?php } add_action('wp_footer', 'tct_accessibilty_window_js');

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

🔒I won't send you spam, I promise