0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bill Riess
  • 334
  • 1
  • 3
  • 10
  • 2
    possible duplicate of [event.preventDefault() vs. return false](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Greg Burghardt Jun 24 '15 at 19:27

1 Answers1

0

I was trying to call preventDefault and stopPropagation on the element, not the event.

The solution would be:

(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(event) {

    if (this.hasClass('clicked')) {
      return true;
    }

    // Prevent default behavior
    event.preventDefault();
    event.stopPropagation();
    
    // Run some code...

    // Add clicked class and recall the click
    this.addClass('clicked');
    this.click();
    
    return false;
  };

  anchor.addEventListener('click', someFunction);

})();
<a href="//google.com" class="selector">Google</a>
Bill Riess
  • 334
  • 1
  • 3
  • 10