Javascript event reacts immediately


#1

Why does window.onclick react here when I click on select_date?

select_date.onclick = function() {

		if (month_parent.style.display != "block") {

			month_parent.style.display = "block";

			window.onclick = function(){
				alert();
			}
 		}
}

I want window.onclick to have the function that I’ve assigned it in the code, but after select_date has been clicked. And when select_date is clicked, I don’t want window.onclick to respond to the same click on select_date. That’s what I thought I created here. (When select_date is clicked, window.onclick should be equal to a declaration / defintion, not a function call)

So what am I missing? Event popping back up to the window after everything has been assigned?

I tried to prevent it with return false, which didn’t work.

Best regards
Neo


#2

Step 1: Capture the event (Define your function with a single parameter)
Step 2: tell that parameter to .preventDefault(), which should prevent bubbling up to the window.


#3

Unless I’m missing the obvious, (highly possible) wouldn’t that be
.stopPropagation() ?


#4

stopPropagation worked. Is there another way to do this that’s supported on all browsers? IE seems to have full support from 9.0


#5

sorry, yes. preventDefault stops the default action, stopPropagation stops bubbling. Just way too used to trying to stop the default action on things :laughing:


#6

If the information is correct (I have no reason to question it), both have been supported in all major browsers for a long time now.
https://caniuse.com/#feat=addeventlistener


#7

Okey.
Thanks alot guys, it’s appreciated.