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>
General Grievance
  • 4,555
  • 31
  • 31
  • 45
GTS Joe
  • 3,612
  • 12
  • 52
  • 94

2 Answers2

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>
Vineesh
  • 3,762
  • 20
  • 37
0

Also we can achieve using "hideFocus" property.

Ex:

document.getElementById('linkURL').hideFocus;