GTS Joe
GTS Joe

Reputation: 4142

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>

Upvotes: 7

Views: 10191

Answers (2)

perumalsamy
perumalsamy

Reputation: 69

Also we can achieve using "hideFocus" property.

Ex:

document.getElementById('linkURL').hideFocus;

Upvotes: 0

Vineesh
Vineesh

Reputation: 3782

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>

Upvotes: 7

Related Questions