Let’s say I have this markup:
<div id="content">
<div id="firstP"><p>First paragraph</p></div>
<div id="secondP"><p>Second paragraph</p></div>
<div id="thirdP"><p>Third paragraph</p></div>
<div id="fourthP"><p>Fourth paragraph</p></div>
</div>
I want to add a new <div>
with jQuery and focus on this new element. .focus
does not do anything.
function addParagraph() {
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$("#content").append(html);
$("#newP").focus();
}
Any idea why?
The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);
focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.
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.
JavaScript | Focus()It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.
I think the main answer is incorrect. DIV and P tags can receive focus providing you specify a tabindex property for them. i.e.
<div class="someclass" tabindex="100">
Once the tabindex is specified you can either tab to these elements or shift focus with .focus() .
Using a scrollTo plugin seems like a bit of an overkill here.
There's no problem with your code, it's just that a paragraph or div tag can't receive focus. Focus can only be given to things you can interact with, such as links, input elements, textareas, etc.
To scroll the window to this newly added element, you can use a plugin such as ScrollTo.
On a side note, your code could be simplified a bit:
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$("#content").append(html);
$("#newP p").focus();
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$(html)
.appendTo('#content')
.focus() // or scrollTo(), now...
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With