简体   繁体   中英

AddEventListener blur doesn't work when JQuery blur() is triggered on the element

I have an input element and have two blur event on the same. First one I added as an eventListener and the second one as onBlur of that element.

I added a button and call a method on button click. The method triggers empty blur event on the element.

It doesn't trigger the onBlur I added as an eventListener.

<form id="form">
  <input type="text" placeholder="text input">
  <input type="password" placeholder="password" id="password" onBlur="Hello();">
  <input type= "button" value ="Click" onClick=TriggerBlur();>
</form>


<script>
const password = document.querySelector('input[type="password"]');
password.addEventListener('blur', (event) => {
  event.target.style.background = 'pink';
});

function TriggerBlur(){
    $("#password").blur();
}

function Hello(){
    alert("Hello");
}
</script>

Here is the jsFiddle: https://jsfiddle.net/17gsozLd/

When you click the button, you will see only an alert. The color of the text field won't change.

Instead of using $("#password").blur();

Use, dispatchEvent:

const event = new Event('blur');
password.dispatchEvent(event);

So, your final code should be like: (without the need of jquery)

 const password = document.querySelector('input[type="password"]'); password.addEventListener('blur', (event) => { event.target.style.background = 'pink'; }); function TriggerBlur(){ const event = new Event('blur'); password.dispatchEvent(event); } function Hello(){ alert("Hello"); }
 <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password" id="password" onBlur="Hello();"> <input type= "button" value ="Click" onClick=TriggerBlur();> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM