Search code examples
javascriptjqueryhtmlfocusonblur

Using jQuery focus and blur to show and hide a message


I am clicking to set focus on a textbox, and once I have set focus I am trying to display a simple message. Then on blur that message disappears.

Here is my code: If I click on the textbox it displays the message but if I click the button it doesn't set focus as I thought it would.

<script>
$(document).ready(function(){    
  $("#clicker").click(function(){        
    $("#T1").focus(function(){            
      $("#myFocus").show();        
    });     
  });        

  $("#T1").blur(function(){        
    $("#myFocus").hide();    
  });
});
</script>

<body>
<div id="clicker" style="cursor:pointer; border:1px solid black; width:70px;">
  Click here!
</div>
<br /><br />
<input id="T1" name="Textbox" type="text" />
<div id="myFocus" style="display: none;">focused!</div>

Solution

  • You need to trigger the focus event, instead of defining it. Try this instead:

    <script>
    $(function() { // Shorthand for $(document).ready(function() {
          $('#clicker').click(function() {
                $('#T1').focus(); // Trigger focus
          });
    
          $('#T1').focus(function() { // Define focus handler
                $('#myFocus').show();
          }).blur(function() {
                $('#myFocus').hide();
          });
    });
    </script>