Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .focus doesn’t actually focus a newly created element

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?

like image 670
Sergio del Amo Avatar asked Dec 02 '08 16:12

Sergio del Amo


People also ask

Why focus is not working jQuery?

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);

Is Focus () deprecated?

focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.

How do you focus an element in 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.

What is focus () in JavaScript?

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.


2 Answers

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.

like image 121
Michal Avatar answered Oct 21 '22 06:10

Michal


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...
;
like image 29
nickf Avatar answered Oct 21 '22 06:10

nickf