How to focus/unfocus elements with dijit/focus
What is Dojo?
The Dojo is a JavaScript toolkit(library) that provides many utility modules and functions to create a web application. We can save time and speed up the development process using the predefined Dojo modules. Dojo includes language utilities, UI components, and more.
Note: Read more about Dojo at their homepage.
The dijit/focus module
Dijit is Dojo’s UI Library. The dijit/focus is a module present in the Dojo library to work with focused nodes and widgets. Using this module, we can get the focused node/widget and track the focus changes.
How to use the dijit/focus module
Load the
dijit/focusmodule using therequirefunction.Call the
focusmethod to focus on an element.Call the
blurmethod to unfocus on an element.
Code example
Let's make a sample example to focus and unfocus a div element using dijit/focus module:
Code explanation
In the above code snippet:
Line 10: We create a
divelements and add width, height, and background color for thedivelement. Add style to add a border when thedivelement is focused. The border will be removed when the element is unfocused.Lines 11 and 12: We create two buttons to focus and unfocus the
divelement. Add the click event listener to those buttons.Line 14: We load the Dojo library from the CDN server.
Lines 29–33: We create a function
loadDijitFocus. This function will use therequirefunction to load thedijit/focusmodule. Once that module is loaded, we assign the focused object to a variableDijitFocus. So that we can use that to focus and unfocus elements.Lines 36–38: We create a function to focus the element. Here we use
focusmethod of theDijitFocusobject.Lines 41 - 46: We create a function to unfocus the element. Here, we use
curNodeproperty of theDijitFocusobject to get the currently focused element. After that, we useblurmethod to unfocus the element.
Free Resources