最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - blur() does not work programmatically | but does when initiated from the user - Stack Overflow

programmeradmin1浏览0评论

This works in clearing in input after a user submits it via ajax on a single input form.

var tweet_input = document.getElementById( 'tweet_input' );
tweet_input.value='';
tweet_input.blur();

However on a 3 input field orm this does not:

var input_url = document.getElementById( 'bookmark_input_url' );
    input_url.value='';
var input_title = document.getElementById( 'bookmark_input_title' );
    input_title.value='';
var input_tag = document.getElementById( 'bookmark_input_tag' );
    input_tag.value='';

input_title.blur();
input_url.blur();
input_tag.blur(); 

Only the last element is actually blurred. Not sure what is going on here with the other two or how to troubleshoot.

Basically I have Event Listeners that fire on a blur(), they work fine on an actual user blur(), but when I try to initiate them programmatically only one works.

This works in clearing in input after a user submits it via ajax on a single input form.

var tweet_input = document.getElementById( 'tweet_input' );
tweet_input.value='';
tweet_input.blur();

However on a 3 input field orm this does not:

var input_url = document.getElementById( 'bookmark_input_url' );
    input_url.value='';
var input_title = document.getElementById( 'bookmark_input_title' );
    input_title.value='';
var input_tag = document.getElementById( 'bookmark_input_tag' );
    input_tag.value='';

input_title.blur();
input_url.blur();
input_tag.blur(); 

Only the last element is actually blurred. Not sure what is going on here with the other two or how to troubleshoot.

Basically I have Event Listeners that fire on a blur(), they work fine on an actual user blur(), but when I try to initiate them programmatically only one works.

Share Improve this question edited Nov 27, 2019 at 17:37 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked May 23, 2012 at 15:22 user656925user656925 1
  • blur() is the opposite of focus(). There can only be one element with focus, therefore you can only blur the last focussed element. What are you trying to achieve here? – Diodeus - James MacFarlane Commented May 23, 2012 at 15:25
Add a comment  | 

2 Answers 2

Reset to default 16

Needs to have focus first.

input_title.focus();
input_title.blur();
...

This works fine in my case:

const fireEvent = (element, eventType="blur") => element && element.dispatchEvent(new Event(eventType));

Now we can call this function from wherever we want to fire any event attached to any element.

fireEvent(input_title)

Reference

发布评论

评论列表(0)

  1. 暂无评论