8

I have a series of Bootstrap buttons like this:

<button :disabled="page === lastPage" type="button" class="btn btn-default" @click="getPage(lastPage)">
    <span class="glyphicon glyphicon-forward"></span>
</button>

But the first line of the getPage method does not work:

event.target.blur();

Which is very strange, because I have another button in another component, on which event.taget.blur() works perfectly:

<button class="btn btn-default pull-right" @click="show()" type="button">Batch
    <span :class="{'glyphicon glyphicon-chevron-down': showForm, 'glyphicon glyphicon-chevron-up': !showForm}"></span>
</button>

Does anyone know why this might be?

EDIT: I think it's when I click inside the SPAN that the blur doesn't work.

EDIT: oh well I solved it - I also need event.target.parentNode.blur() as well.

1
  • If you solved it, write an official answer and mark it as such. It will give more clarity to those with similar issues and you'll score some points for it. :)
    – jusopi
    Commented Dec 19, 2016 at 15:21

3 Answers 3

31

You likely want to use

event.currentTarget.blur()

That will always be the element you attached the event listener to where as event.target is the element the event originated from.

1
  • Simple answer and nice supplementary comment!
    – dance2die
    Commented Jul 15, 2021 at 7:33
4

I would consider using

if (document.activeElement != document.body) {
    document.activeElement.blur()
}

rather than navigating through nodes as it is less prone to error if the mark up changes.

2

In this case, because the button contains a span, sometimes the user was clicking on the button itself, and sometimes on the span within. Hence, to reliably blur the button I needed:

event.target.blur();
event.target.parentNode.blur();
4
  • 3
    You likely want event.currentTarget.blur(), currentTarget is always the element with the listener added. Commented Dec 19, 2016 at 16:30
  • @BillCriswell even better. If you want, add this as the answer and I will accept. Commented Dec 19, 2016 at 16:38
  • 1
    Added the answer. Commented Dec 19, 2016 at 17:16
  • It works even two parents up event.target.parentNode.parentNode.blur(), nice!
    – Kesarion
    Commented Jun 5, 2019 at 12:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.