cityFoeS cityFoeS - 4 months ago 9
HTML Question

i have an issue with .focus() on an input

Here I have an input that I like with a cursor that I thought was nice. I would like this input to be "focused" on when my window is loaded up so that the cursor is blinking and the input is ready to type in. I use jquery to make the cursor work but cannot make the .focus() function work

https://jsfiddle.net/cityFoeS/z9Ldt/233/

This is my jquery:

$(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

$(function(){ }); is the same as $(document).ready(function () { })

It fires when the document has been parsed and is ready.

You have the $('#text').focus(); outside of this snippet and that piece of code is being executing before the document.ready. So onclick and onblur functions weren't setted yet.

You can try this. If you change your js and simulate click action of "cmd" div after attach the function, it works:

 $(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' });    
  });


});