Reputation:
I have 2 elements. The first element has a blur
event, and the second element has a mousedown
event. The mousedown
event on the second element returns the focus to the first element, but blur
on the first element is triggered for some reason, even if the first element wasn't focused before mousedown
ing the second element.
Why does this happen? Is this (somehow) desired behaviour, or is this some kind of bug?
<!DOCTYPE html>
<html>
<head>
<title>Bug?</title>
</head>
<body>
<input type="text" />
<br /><br />
<button>Click me to focus on the input</button>
<br /><br />
<input type="text" />
<script type="text/javascript">
document.getElementsByTagName('input')[0].addEventListener('blur', function(e){
console.log('blur', e);
});
document.getElementsByTagName('button')[0].addEventListener('mousedown', function(e){
console.log('mousedown', e);
document.getElementsByTagName('input')[0].focus();
});
</script>
</body>
</html>
https://jsfiddle.net/rsh5aopg/
Upvotes: 0
Views: 2988
Reputation: 2119
This is not a bug, the event sequence is:
mousedown
blur
mouseup
click
When you press the button, the mousedown
event is triggered. Within that listener, you focus the first input. Naturally, after the mousedown event, the blur event happens. This takes away focus from first input and you see the blur listener code execute.
You can either add e.preventDefault()
to the mousedown event, or use either mouseup
or click
as those both happen after the blur. Either way, the first input will still have focus as you desire.
Upvotes: 7