$(function() { $(function() { $(".A").focus(); }); $(".A").blur(function() { alert(0); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="A" tabIndex="1"> <input type="text> <a href=" ">Tra-ta-ta</a> <div> <input type=text"> </div> </div> 

The event fires even if I set the focus to text fields that are children of "A". How to make that blur does not work on children?

  • Do I need blur to work or not to work? - lexxl
  • You have not copied the js-code completely, the first line is missing. - Sergey Gornostaev
  • $(function () { $(function () { $(".A").focus(); }); $(".A").blur(function () { alert(0); }); }); - aat

3 answers 3

If option with $('.A input'); does not fit, then I recommend simply checking the elements in the event.

 $('.A').blur(function (evt) { if (evt.currentTarget !== evt.target) return; alert('0'); }); 

evt.currentTarget - the element on which we attached the event.

evt.target - the element on which the event actually occurred.

It should be clarified that the focus and blur events are intended for input . On the blocks it is better to hang the event mousedown and mouseup

     $(function() { $(".A input").blur(function() { alert(0); }); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="A" tabIndex="1"> <input type="text"> <a href="">Tra-ta-ta</a> <div> <input type="text"> </div> </div> 

    • Thank you, but they did not understand me correctly. If a Focus event is set on a block, the blur event for it should not work if I click on the children. - aat
    • Try through mousedown outside this block - sivik_xes

    Perhaps you can use the event focusout instead of blur.

     $(document).ready(function(){ $('.A').bind('focusin focusout', function () { $(this).toggleClass('showup'); }); }); 
     .A { margin-top:20px; margin-left:20px; background:black; height:100px; width:200px; } input { width:80px; margin:5px; } .showup { background: #aaa;} 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="A"> <input type="text"> <a href="#">Tra-ta-ta</a> <div> <input type="text"> </div> </div> 

    • Thank you, but they did not understand me correctly. If a Focus event is set on a block, the blur event for it should not work if I click on the children - aat