简体   繁体   中英

onblur - how to tell what was clicked; or how to tell if an onclick event is waiting to be run

In the code below, is there a way to set blurredByClickOnLink to the correct value (without using mouseover or other pointer events to set something before the click happens)? It should be true if the user blurs the text box by clicking on the link, and false if the user blurs the text box by tabbing or clicking anywhere else. Thank you for taking a look!

<html>
<body>
<input id="myInput" type="text" onblur="var blurredByClickOnLink='???'; console.log('input onblur. blurred by click on link = ' + blurredByClickOnLink);" />
<br/><br/>
<a id="myLink" href="javascript:console.log('a href');void(0);" onclick="console.log('a onclick');">Link</a>
</body>
</html>

When an event occurs on the DOM, that event is "atomic" in nature. That means that the event will be processed from the event queue and only then will the next event be processed. These events are not "grouped" together in any fashion.

When your input element loses focus, that will trigger a blur event upon it. At that point, you can now ask questions about the blur . However there won't be any other state change in the rest of the environment. What happens next may be a click on the link element which can also cause an event to fire. In this case, a click event on the link. Since these happen one after the other ... first a blur on the input and then ... later ... a click on the link, you can't know when the blur happens that the next thing to happen will be a click on the link as it hasn't happened yet.

One possible solution would be to set a short timer on the blur of the input. This timer could fire another function (in say 100msecs) that would then ask the question .. was the link clicked?

This might be sufficient for your puzzle.

The way it helps me to think about such problems is to visualize a queue of requests (an in-box) that the browser processes one-by-one to change the state of the DOM. Ask yourself "When I handle a request, do I have what I need to make a decision?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM