I’m building an AJAX navigable site (code taken from CSS-Tricks) that uses regular links in the markup, but replaces them with hash links via .js.
I don’t want users to be able to click on a link that would just reload the same content. Because I’m using hashes, for any page other than the home page (on first load), this problem solves itself (if a user clicks on a hash link for the current URL hash, nothing happens).
I had a solution that was working until I defined this as a function (since I need to reuse it). It used $(this) to get the link that had been clicked and returned false if it was to the current page. However, now this returns the window (as an array object) rather than the clicked link.
How can I select the clicked link instead?
// Use hashes instead of reloads to navigate the site.
function initiateHashNav(linkContainers) {
var $this = $(this);
$(linkContainers).delegate('a', 'click', function() {
// Restrict clicking on link for current page.
if ($this.attr('href') == window.location.href) {
return false;
} else {
// The hash shouldn't contain window.location (clean URLs are happy URLs!).
window.location.hash = $this.attr('href').substr(window.location.origin.length);
return false;
}
});
}
Just move the declaration of
$thisinto the correct scope like this:Every function in javascript is a scope. Each scope in has a context (this) and if one is not set, the window object becomes the context.
jQuery.fn.delegate sets the matched element as context in the eventhandler, thus
thisis a HtmlAncherElement inside the delegate event handler. But outside in the functioninitiateHashNavthere is no set context,and so it is just the window object