javascriptblurfocusout

How to Trigger a Focusout Event Programmatically


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>


Solution

  • 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>