Hello dear Earthlings,
The code snippet below is currently implemented on my website brianjenkins94.me for handling basic navigation functionalities. After some recent changes, I encountered an issue with the #nav.on("click") event handler not working as expected, and the cause has been elusive to me so far.
If anyone could shed light on why this code isn't functioning properly or suggest a more efficient approach (I'm always striving for best practices and proper design, this bug just gave me a reason to seek advice), your insights would be highly valued.
Thank you in advance,
Brian
/// <reference path="jquery.d.ts" />
"use strict";
const SERVERNAME: string = "http://brianjenkins94.me/";
//const DOCUMENTROOT: string = "https://rawgit.com/brianjenkins94/local.blog.com/master/";
class Navigation {
private body: JQuery;
private nav: JQuery;
private navToggle: JQuery;
constructor(args: any[]) {
this.body = args[0];
this.nav = args[1];
this.navToggle = args[2];
}
public init(): void {
this.stopPropagation();
this.addClickListener(this.body);
this.addClickListener(this.navToggle);
this.addClickListener(this.nav);
this.addKeyCodeListener(27);
this.addLinkListener();
}
private stopPropagation(): void {
(this.nav).on("click touchend", function(event: Event): void {
event.stopPropagation();
});
}
private addClickListener(target: JQuery): void {
(target).on("click touchend", (event: Event) => {
if (!(target === (this.body))) {
event.preventDefault();
event.stopPropagation();
if (target === this.navToggle) {
(this.body).toggleClass("nav-visible");
return;
}
}
(this.body).removeClass("nav-visible");
});
}
private addKeyCodeListener(keycode: number): void {
$(window).on("keydown", function(event: JQueryKeyEventObject): void {
if (event.keyCode === keycode) {
(this.body).removeClass("nav-visible");
}
});
}
private addLinkListener(): void {
// FIXME: This can be optimized.
$("#nav .links a").click(function(event: Event): void {
if (!$(this).hasClass("active")) {
$("#nav .links a").removeClass("active");
$(this).addClass("active");
document.location.hash = $(this).attr("href");
switch (document.location.hash) {
... (content truncated)
}
} else {
// Same link
$("#nav .links a").removeClass("active");
$(document.location.hash).click();
console.log("Simulating " + document.location.hash + " link click.");
}
});
if (document.location.hash.length === 0) {
$("#home").click();
console.log("Simulating #home link click.");
} else {
$(document.location.hash).click();
console.log("Simulating " + document.location.hash + " link click.");
}
}
}
var Nav: Navigation = new Navigation([$("body"), $("#nav"), $("a[href=\"#nav\"]")]);
Nav.init();