0
votes

How HTML attribute onblur and jQuery .trigger("blur") event work?

will both events execute like javascript this.trigger("blur") work first and then HTML attribute onblur work or only one event will be fired?

I am using onblur attribute on an input element and in some scenarios I have triggered that event using javascript but my function is executing multiple times. I think the blur event fired two times, so how I can fired it only once?

Here is HTML element.

<input class="form-control"
       type="text"
       id="ListDisplay"
       onblur="changeVal()"
       autocomplete="off"
       value="${name}"
       display="${name}"
/>

Here is the jquery event on which blur triggered. in this showSuggestionListItem is a dynamic dropdown.

$(".showSuggestionListItem").off('mousedown').on('mousedown',
  function () {
    $('#ListDisplay').trigger("blur");                          
  }
);

Here is changeVal function of onblur.

function changeVal(){
    alert('called');
}
1
what is elem? what is . showSuggestionListItemepascarello
@epascarello, I have updated the code, thanks for the correction.Rahul Sharma
Why don't you simply call that function instead of calling/triggering irrelevant obfuscating events? Think as a programmer, if you need to call changeVal you immediately know what you're doing. If instead you call .blur() or trigger("blur") you have to go throughout the entire codebase to lookup and understand what it's supposed to do and what will happen in return. .on('mousedown', changeVal) is way cleaner than anything else.Roko C. Buljan
Please provide a Minimal, Reproducible Example: stackoverflow.com/help/minimal-reproducible-example Your current example is confusing and does not make a lot of sense.Twisty

1 Answers

0
votes

Using onBlur attribute simply assigns the callback to the Blur event. .trigger("blur") triggers a blur event.

As you have a trigger in another event, the act of clicking outside of the text field triggers a blur event that may bubble up before the mousedown event; hence why you get two blur events triggered.

I would advise the following.

$(function() {
  function changeVal() {
    console.log('Blur called');
  }
  $("#ListDisplay").blur(changeVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="ListDisplay" autocomplete="off" value="${name}" display="${name}" />