JavaScript Click Event Handling

So, I attach an event to a document to watch when a click event occurs on a specific anchor with a class yui3-pjax

, in some cases the anchor has a child span. How can I watch for anchor-only event bubbles? My current if-statement to view the event:

document.addEventListener('click', function(evt) {
  if(evt.target.classList.contains('yui3-pjax') || evt.target.parentNode.classList.contains('yui3-pjax')) {
    // do stuff
  }
});

      

HTML snippets

<a class="page_current yui3-pjax" href="/forum/chatterbox/last-person-to-reply-wins/t.94028885_991/" title="page 67">
  67
</a>
<a class="yui3-pjax cta-button-sm gray-button postitem-link pull-right" href="/forum/chatterbox/last-person-to-reply-wins/t.94028885_991/">
  <span>67</span>
</a>

      

I'm not sure if there is a better way than looking at both the anchor and the parent of the span element (the same anchor) without binding it to the anchor itself, but the problem with that is some of the anchors are dynamically generated and this

obviously won't work, so how it will link to the document. Any ideas?

Edit: I think there is some kind of confusion about what I am asking. Let me be clear, I only need to check the anchor if it has a yui3-pjax class. I'm not sure how to handle propagating / bubbling an event from a child or descendant of this anchor in order to achieve this.

+3


source to share


1 answer


I hope I understand this correctly. Instead of manually checking the element and parent for a specific class, I would instead write a function that returns a DOM object to find out if the event target is contained in an element with a given class. This way, you don't have to write code that relies on the HTML structure, but it rather dynamically determines whether your element lives inside an element with (for example) the "yui3-pjax" class. Note. I don't check if an element with class "yui3-pjax" is an anchor, but you can add it if needed. Check out the fiddle http://jsfiddle.net/9L0jce6x/ .



document.addEventListener('click', function(evt) {
    if(elementOrParentsHaveClass(evt.target, 'yui3-pjax')){
        //do stuff
    }
});

//Recurse up the DOM until we find a parent with the given class, or return false if we don't
function elementOrParentsHaveClass(elem, className){
    if(elem && elem.classList.contains(className)){
        return true;  //yay!
    }else{
        //Recurse only if parent exists
        if(elem.parentNode){
            return elementOrParentsHaveClass(elem.parentNode, className);
        }
        else{
            //If the parent node does not exist, end recursion - we finished recursing up the DOM
            return false;
        }
    }
}

      

+1


source







All Articles