admin管理员组

文章数量:1297030

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>

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>

Share Improve this question edited Apr 27, 2023 at 19:20 General Grievance 5,03338 gold badges37 silver badges56 bronze badges asked Mar 12, 2018 at 4:45 GTS JoeGTS Joe 4,19217 gold badges61 silver badges109 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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>

Also we can achieve using "hideFocus" property.

Ex:

document.getElementById('linkURL').hideFocus;

本文标签: javascriptHow to Trigger a Focusout Event ProgrammaticallyStack Overflow