Remove element Focus using pure Javascript

Asked

Viewed 5,447 times

0

I want to know how to remove the focus of an element when it is clicked using pure Javascript.

I did it this way using jQuery

$(function(){
  $(".btn").click(function(){
    $(".btn").blur();
  });
});

This served me very well, however, I changed some things on the site and jQuery was almost useless. It would be an exaggeration to include jQuery on a site just to do this.

3 answers

3


Try this, it is proposed in case you have several elements with the class="btn". You will use the same function blur():

var btn = document.getElementsByClassName("btn");
for (var i = 0; i < btn.length; i++){
    btn[i].addEventListener('click', function(){
         this.blur();
    });
}

2

This jQuery code does 3 things:

  • expects the tab to click to run the code
  • adds an event receiver to each element with the class .btn
  • removes focus, ie does .blur() to all elements with the class .btn

I assume that in the third step it is only interesting to take the clicked element out of Focus, and not to waste time with others. You can do this in native Javascript:

window.onload = function () { // só corre quando a página tiver carregado
    function blur() {
        this.blur(); // o JavaScript nativo também têm este método blur   
    }
    var btns = document.querySelectorAll('.btn');
    for (var i = 0; i < btns.length; i++) { // percorre todos os elementos
        btns[i].addEventListener('click', blur); // adiciona o auscultador de eventos
    }
}

1

The function is the same: blur().

Example:

var button = document.querySelector('button');

button.addEventListener('click', function() {
  this.blur();
});

button.addEventListener('blur', function() {
  alert('Perdeu o Foco.');
});
<button>Remover foco</button>

To get all the elements you can use document.querySelectorAll.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.