55

After the ajax function is over. in success messages I'm focusing to the specific div. But it's not working. My code is here.

$j.ajax({
    url:"<?php echo admin_url( 'admin-ajax.php' ); ?>",
    type:"POST",
    data:"action=press_release&page="+0+"&do_task="+do_task+"&id="+id+"&module="+module,
    success:function(data){
        $j("#com_cont").show();
        $j("#com_cont").html(data);
        $j("#loading_heart").hide();
        $j("#focus_point").focus();
    }
});

This is the code is not working(Not focusing on the div:$j("#focus_point").focus();

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Miko
  • 2,615
  • 9
  • 33
  • 58

3 Answers3

133

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();
suDocker
  • 8,504
  • 6
  • 26
  • 26
  • 1
    This is what i've seen as well but I can't get it working for Ie8 or Ie7 – Josh Bedo Sep 07 '12 at 15:14
  • I can't seem to get this working for Ie8 or Ie7 either I've also seen that you need to add setTimeout so it gives the event some extra time – Josh Bedo Sep 10 '12 at 17:51
  • +1 Definitely the correct answer in terms of actual focus, try tabbing one the accepted answer and focus returns to the beginning, this one starts on the focus point. – DasBeasto Dec 17 '15 at 14:06
  • Make sure that $j("#focus_point") isn't an element that users with accessibility needs would need to tab to. Setting tabindex to -1 will make it untabbable, and removing the tab outline would make it so the user wouldn't see the outline when tabbed to. – Chad Jun 13 '18 at 13:57
83

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
derek
  • 4,826
  • 1
  • 23
  • 26
22

Focus doesn't work on divs by default. But, according to this, you can make it work:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

gearsdigital
  • 13,915
  • 6
  • 44
  • 73
Amy Anuszewski
  • 1,843
  • 17
  • 30