Remove element focus using pure JavaScript

0

I want to know how to remove focus from an element when it is clicked using pure JavaScript.

I made it that way using jQuery

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

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

    
asked by anonymous 29.11.2015 / 22:00

3 answers

2

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

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

This jQuery code does 3 things:

  • expects the page to run to run the
  • adds an event dropper to each element with class .btn
  • remove focus, ie make .blur() to all elements with class .btn

I assume that in the third step it is only interesting to focus on the clicked element, and not 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
    }
}
    
29.11.2015 / 22:21
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 .

    
29.11.2015 / 22:12