I'm trying to register a new click event on an element that will fire once, run it's code then execute any other bound events or default methods.
For example:
User clicks an anchor, a function executes and once complete the anchor continues it's default behavior. Ideally this should execute my function first in case there are other click events bound to the anchor.
Here is what I was trying:
(function() {
// Link
var anchor = document.querySelector('a.selector');
// Helpers
Element.prototype.hasClass = function(className) {
return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};
Element.prototype.addClass = function(className) {
return this.className = this.className + " " + className;
};
// Click function
var someFunction = function() {
if (this.hasClass('clicked')) {
return true;
}
// Prevent default behavior
this.preventDefault();
this.stopPropagation();
// Run some code...
this.addClass('clicked');
this.click();
return false;
};
anchor.addEventListener('click', someFunction);
})();
<a href="//google.com" class="selector">Google</a>
I've added preventDefault and stopPropagation but the link still continues through for me.