How can I trigger the focus() event for the textarea element using code? To happen the same thing as when you click on the textarea field with the mouse. That is, the selection (textarea: focus style), well, when you press the keys, the text is entered into the field.

Tried .focus() , .select() , and other methods, but they don't work.

  • Show the code, people guess that yes how did you try? - Air
  • @Air read the whole question - Vlad
  • It is clear that the code ... And at what event this code should work? Under what circumstances? Describe the question normally ... - Air
  • @Air $ (textarea) .focus () that works, but the fact is that with the focus by the function mentioned, the text, the textarea: focus {//} does not work for the text, but with manual focus, the styles are applied. - Vlad
  • @Vlad I already left you a message below. The focus of the textbook is executed, the focus event is processed. Accept the answer or state your thoughts correctly. You can restart, for you the trigger was added specifically to initiate events without a user. - EVG

4 answers 4

 $('textarea').focus(function(e){ alert('Работает же')}) $('textarea').trigger('focus') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea cols="100" row="100"> </textarea> 

  • Enter $ ('. Snippet-code textarea'). Focus () in the console of the browser, there will be no alert. And I'm just trying to do so in order to perform the focus of the text code, and not by clicking manually. - Vlad
  • @Vlad maybe because it's not there?)))) Execute the code above as an example, everything works out ...) - EVG

This is not an answer, this is a question)))) Explain to me that things may not work here ?????

 textarea{ background:red; } textarea:focus{ background:green; } 
 <textarea cols="100" row="100"> </textarea> 

     $('textarea').trigger('focus'); 
    • Tried, does not work. - Vlad

     $(function(){ $(document).on("focus","textarea", function(){ console.log("textarea focus"); }); $('textarea').focus(); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <textarea>con</textarea> 

    • Strange, logged in the console, and the outline (blue frame) with focus code does not appear - Vlad
    • one
      @Vlad What does not appear? blue frame? Why does not appear))) I see it now, change / update / delete the browser - Arsen