For those who are interested, I made a triple version of the if block with a check to find out which classes the element has and which class is bound.
$(document).ready(function () { $("a").click(function (e) { var hostname = new RegExp(location.host); var url = $(this).attr("href"); hostname.test(url) ? $(this).addClass('local') : url.slice(0, 1) == "/" && url.slice(-1) == "/" ? $(this).addClass('localpage') : url.slice(0, 1) == "#" ? $(this).addClass('anchor') : $(this).addClass('external'); var classes = $(this).attr("class"); console.log("Link classes: " + classes); $(this).hasClass("external") ? googleAnalytics(url) : $(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local"); }); });
The Google Analytics bit can be ignored, but this is where you probably would like to do something with the URL to find out what type of link it has. Just add the code inside the triple block. If you want to check only 1 type of link, replace tees with an if statement instead.
Edited to add a problem that I encountered. Some of my hrefs were "/ Courses /". I checked the local page, which checks if there is a slash at the beginning and end of the href. Although, probably, it is enough to check for the presence of "/" at the beginning.
George F Delaney Mar 23 '16 at 10:48 2016-03-23 10:48
source share