***UPDATED JSFIDDLE (this is a more accurate representation of what I am dealing with -- second box shouldn't open if the open one is not valid)
I have searched and searched for this answer, even the ones that are opposite (like why isn't my click happening after the blur) don't answer my question. Hopefully someone can clarify.
I am using a proprietary API. There is a click event that is registered on this element I'm interested in. I need to do some work before this click and depending on the outcome of this work, I may not even want this click to happen. Obviously I cannot change the inner working of the API, so I am left with having to do something else.
I have tried just adding another click, but it won't call it first before the second click (in the API) because from what I read, they are called in the order of registration and the API registers theirs first.
I have tried a blur, which does get called before their click event, but preventDefault(), stopPropagtion() and stopImmediatePropagation(), and return false have done nothing to stop that click event.
Pretty much my method is a validation that if its good, the API's click event should happen... but if its not, then I need to to "not" click.
Besides using unbind with jQuery (which I haven't tested because I'd rather use native Javascript), I am unsure how I can do this.
here is JSFIDDLE
var d = document.getElementsByClassName('testDiv');
for (var i = 0; i < d.length; i++) {
d[i].addEventListener('click', function(e) {
//alert('hi');
e.target.style.backgroundColor = 'blue'; //this shouldn't happen if not valid
});
d[i].addEventListener('blur', function(e) {
//alert('I\'m blurred now');
var valid = false
if (!valid) {
//e.stopImmediatePropagation(); //didn't work
console.log('not valid');
//return false; //didn't work
/*** if its not valid we want to cancel the click event ***/
}
else {
e.target.style.backgroundColor = '#c486d0';
e.target.innerHTML = 'Blurred';
}
});
}