I am experiencing a problem with using the .focus() method with an input field

When my window loads, I want the cursor in this input to be blinking and ready for typing. I have tried using jQuery to make this happen, but for some reason I can't get the .focus() function to work properly.

Check out my code on JSFiddle

This is the jQuery snippet I'm using:

$(function() {

var cursor;

$('#cmd').click(function() {
   $('input').focus();

  cursor = window.setInterval(function() {
  if ($('#cursor').css('visibility') === 'visible') {
    $('#cursor').css({ visibility: 'hidden' });
  } else {
    $('#cursor').css({ visibility: 'visible' });  
  }  
  }, 500);

});

$('input').keyup(function() {
  $('#cmd span').text($(this).val());
});

$('input').blur(function() {
   clearInterval(cursor);
   $('#cursor').css({ visibility: 'visible' });    
});

});
$('#text').focus();

Answer №1

$(function(){ }); is essentially the same thing as

$(document).ready(function () { })

It triggers when the document has finished parsing and is ready for manipulation.

The issue arises from having $('#text').focus(); placed outside of this code snippet, causing it to execute before the document.ready event. As a result, onclick and onblur functions are not yet set up.

A possible solution is to modify your JavaScript to initiate a click action on the "cmd" div only after all necessary functions have been attached:

 $(function() {

var cursor;

$('#cmd').click(function() {
   $('input').focus();

  cursor = window.setInterval(function() {
  if ($('#cursor').css('visibility') === 'visible') {
    $('#cursor').css({ visibility: 'hidden' });
  } else {
    $('#cursor').css({ visibility: 'visible' });  
  }  
  }, 500);

});

$('#cmd').click();

$('input').keyup(function() {
  $('#cmd span').text($(this).val());

});

  $('input').blur(function() {
     clearInterval(cursor);
     $('#cursor').css({ visibility: 'visible' });    
  });


});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vuetify: The checkbox displays the opposite status of whether it is checked or unchecked

Can you help me simplify this problem: In my Vue.js template using Vuetify components, there is a checkbox present: <v-checkbox v-model="selected" label="John" value="John" id ="john" @click.native="checkit"> </v-checkbox> ...

What is the best way to animate specific table data within a table row using ng-animate?

Are you working with Angular's ng-repeat to display a table with multiple rows? Do you wish to add an animation effect to specific cells when a user hovers over a row in the table? In the scenario outlined below, the goal is to have only certain cell ...

before the ajax response is received, running ahead

I've encountered an issue where I'm attempting to execute a function after an ajax return has finished using then, but it appears to be running before the return completes. Here is the code snippet in question: var existingUser = false; $.ajax( ...

What causes the datepicker to flicker in React when an input field is in focus?

Can someone explain why the datepicker is flickering in React when focusing on the input field? I have integrated the following date picker in my demonstration: https://www.npmjs.com/package/semantic-ui-calendar-react However, it is flickering on focus, ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...

Exploring the 3D Carousel Effect with jQuery

After creating a 3D carousel using jQuery and CSS3, I am looking to enhance it with swiping support. While there are plenty of libraries available for detecting swipes, I specifically want the carousel to start rotating slowly when the user swipes slowly. ...

alter information in a javascript document

Hey there, I've got a JavaScript array of URLs in my content.js file. I want to show these URLs in separate input boxes on a different page called display.php. Each input box will have edit and delete buttons. Any changes made by the user should updat ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

use in jQuery.each

Is there a way to implement jQuery.each so that if a match is found within the array being processed, the iteration can be halted without processing the remaining elements? <ul> <li>foo</li> <li>bar</li> You can achieve thi ...

Can you explain the distinction between id and _id in mongoose?

Can you explain the distinction between _id and id in mongoose? And which one is more advantageous for referencing purposes? ...

How can we incorporate Django template tags into our jQuery/JavaScript code?

Is it possible to incorporate Django's template tags within JavaScript code? For example, utilizing {% form.as_p %} in jQuery to dynamically inject forms onto the webpage. ...

Semantic UI utilizes floating elements to position them within a

As a beginner with Semantic UI, I have been unable to find any information in the documentation on how to float a simple element without it needing to be nested within another element like a button or a segment. For example, at the bottom of a page, I hav ...

Develop a real-time streaming service using AngularJS

I am looking to develop a website that pulls information from multiple APIs and presents it in a user-friendly format. Since I wanted to experiment with AngularJS, I opted to use it for this particular project. However, I am struggling with figuring out h ...

What exactly is the significance of "utilizing a universal class name"?

In my current project, I am utilizing Material-UI version 3.1.2 to create the interface. Previously, when I was using Bootstrap4, I included style="overflow-y: scroll; height: 100%" in my head tag to ensure a scrollbar is always present, preventing the ap ...

The function of window.location is not responsive when used in conjunction with an ajax

The main page redirect occurs in 2 scenarios: When the user clicks logout When the session expires Code for logout functionality: $("#logoutLink").click(Logout); function Logout() { $.post("Logout", { antiCSRF: '{{acsrf}}&apo ...

Retrieve the order in which the class names are displayed within the user interface

In the following code snippet, each div element is assigned a common class name. <div id="category_9" class="list_item" data-item_ids="[38]"</div> <div id="category_2" class="list_item" data-ite ...

Nesting an ajax call within the success function of another ajax call using jQuery's .each method

I encountered an issue with my ajax call that retrieves data containing latitude and longitude values. $.ajax( { url: 'json/data.json', dataType : 'json', type: 'get', cache: false, success: function(fullJSONData ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

AngularJS $routeProvider not working as expected

Today marks the beginning of my journey with AngularJS, and I'm facing a roadblock in the "routing" aspect. I've successfully created a controller and a view (refer below), but upon attempting to run it on my local server, an error pops up: Unca ...

Tips for customizing tab pane color using HTML/CSS

I am looking to customize the color scheme of my tab-pane. My goal is to have each tab turn "orange" when clicked, while keeping the rest of the tabs in a "gray" color. Below is the code I am currently experimenting with: <!-- Nav tabs --> <ul ...