Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus div? [duplicate]

Tags:

html

jquery

Please don't throw stones at me because i'm total newbie at js and jquery. is it possible to focus a div? i just wanted to process events when div is clicked OR is focused and when we click outside the div. Something like that:

HTML:

<div id="focusedDiv"></div>

JS:

    $("#focusedDiv").focus(function () {
        ....
    });

    $("#focusedDiv").focusout(function () {
        ....        
    });

Thanks in advance!

like image 865
user1178399 Avatar asked Jun 11 '13 10:06

user1178399


People also ask

Can we apply focus on div?

Yes - this is possible. In order to do it, you need to assign a tabindex... A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

How do I move focus from one div to another?

Use parent() to select the parent <div> , move to the next() DIV, and find() the child input to focus on it. Note that you should add :first in order to apply the function on the first input .

How do I make a div not focusable?

In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction. In order to prevent an element from being tabbed to, use tabindex=-1 attribute. Adding tabindex=-1 will make any element focusable, even div elements.

Can we focus on a div jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.


1 Answers

You have to set tabindex attribute:

http://jsfiddle.net/QAkGV/

<div id="focusedDiv" tabindex="-1"></div>

Or:

$("#focusedDiv").attr('tabindex',-1).focus(function () {
        ....
    });

For style, you could set outline CSS property too:

$("#focusedDiv").css('outline',0).attr('tabindex',-1).focus(function () {
        ....
    });
like image 79
A. Wolff Avatar answered Oct 14 '22 11:10

A. Wolff