JavaScript On-Click, Event Listeners and Binding
Delegated
An event-delegation approach to on
attaches an event handler to only one outer element #my-nav
, and the inner element’s event (click
on a.item
) only bubbles up one level. This also allows you to dynamically add new a.item
elements to #my-nav
which will immediately bind.
$('#' + target_id).on('click', 'a.item',
function(e)
{
e.preventDefault(); // Stops the normal element action.
console.log( $( this ).text() );
}
);
Click outside to close
$(document).mouseup(function(e) {
var container = $("YOUR CONTAINER SELECTOR");
// If the target of the click is not the element
// or a descendant of the element, hide it.
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
Ctr+Click (open in new window/tab)
// Check "open in new window/tab" key modifiers
if (e.shiftKey || e.ctrlKey || e.metaKey) {
window.open(link, '_blank');
} else {
window.location.href = link;
}
Bind to keyboard
"use strict";
// Called when a key is pushed.
function key_down(key_id, name) {
var element = document.getElementById('key_' + name);
element.classList.add('active');
}
// Called when a key stopes being pushed.
function key_up(key_id, name) {
var element = document.getElementById('key_' + name);
element.classList.remove('active');
}
// Detect a key push.
document.onkeydown = function (e) {
// Get the event.
e = e || window.event;
// Identify which key by its code.
switch (e.which || e.keyCode) {
case 37:
key_down(37, 'left');
break;
case 38:
key_down(38, 'up');
break;
case 39:
key_down(39, 'right');
break;
case 40:
key_down(40, 'down');
break;
default:
return;
}
e.preventDefault();
};
// Detect a key-up.
document.onkeyup = function (e) {
// Get the event.
e = e || window.event;
// Identify which key by its code.
switch (e.which || e.keyCode) {
case 37:
key_up(37, 'left');
break;
case 38:
key_up(38, 'up');
break;
case 39:
key_up(39, 'right');
break;
case 40:
key_up(40, 'down');
break;
default:
return;
}
e.preventDefault();
};