Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(I've included two methods here: One method uses jQuery, and the other doesn't use jQuery. Skip down to the bold heading if you don't want to use jQuery)</p> <p>One way you could do this is by adding a class to each external link, and then attaching an event handler to everything in that class which raises an alert when you click the link. That's tedious, though, as you have to add the class to <em>every</em> external link, and it won't for user generated content.</p> <p>What you can do is use jQuery, along with the CSS selector <code>a[href^="http"]</code>, to select all the external links, and then attach an event handler that raises your alert when they're clicked:</p> <pre><code>$('a[href^="http"]').click(function() { alert(); }); </code></pre> <p><code>a[href^="http"]</code> means "an <code>a</code> tag which has a link, and that link has to start with 'http'." So here we select all the elements which start with <code>http</code> - that is, every external link - and then set it so that when you click on them, an alert pops up.</p> <p><strong>Non-jQuery method</strong></p> <p>If you want to do this without jQuery, you'll want to use <code>document.querySelectorAll('a[href^="http"]')</code> and bind the click event of each element in the array that that function returns. That looks something like this:</p> <pre><code>var externalLinks = document.querySelectorAll('a[href^="http"]'); for (var i = externalLinks.length-1; i &gt;= 0; i--) { externalLinks[i].addEventListener("click", function() { alert(); }, false); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload