How to Trigger a Focusout Event Programmatically
Asked Answered
F

2

7

How can I trigger a focusout event programmatically using just JavaScript not jQuery?

For example, in the following code, the idea is that it should alert "Hello, world!" because of the focusout() function (or a similar event-causing function) being called (focusout() isn't a JS function but that's the idea).

function helloWorld () {
  alert('Hello, world!');
}

document.getElementsByTagName( 'form' )[0].addEventListener( 'focusout', function( eventObj ) {
  helloWorld();
});

var event = new Event('focusout');
document.getElementsByTagName( 'form' )[0].dispatchEvent(event);       
<form action="" method="post" id="sampleForm">
	<input type="text" id="linkURL" name="linkURL" placeholder="Link URL"><br>
  <input type="submit" name="action" value="Submit">
</form>
Fairground answered 12/3, 2018 at 4:45 Comment(0)
S
7

You can do it using Event constructor.

function helloWorld () {
  alert('Hello, world!');           
}

var event = new Event('focusout');
document.getElementsByTagName( 'form' )[0].dispatchEvent(event);  

document.getElementsByTagName( 'form' )[0].addEventListener( 'focusout', function( eventObj ) {
  helloWorld();
});
<form action="" method="post" id="sampleForm">
	<input type="text" id="linkURL" name="linkURL" placeholder="Link URL"><br>
  <input type="submit" name="action" value="Submit">
</form>
Sieracki answered 12/3, 2018 at 4:55 Comment(1)
Didn't work for me, I simulated it by focusing on an input boxMonahon
D
0

Also we can achieve using "hideFocus" property.

Ex:

document.getElementById('linkURL').hideFocus;

Domela answered 27/1, 2021 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.