Search code examples
jquerybuttonfocushighlightingblur

set focus to button on tab


Hi I am trying to set focus to a button when it is tabbed to. The problem I am having is that when i add in the background image for the button the focus color is not being shown around the image but if I remove the image the button works great. How can I put a border around the button when it has focus and reset it on blur?

<html>
 <head>

 <script type="text/javascript" src="jquery-1.3.2.min.js"></script>


<script type="text/javascript">

$(document).ready(function() { 
  $('button:button').focus(function(){ 
    $(this).css({'background-color' : 'red'}); 
  }); 
  $('button:button').blur(function(){ 
    $(this).css({'background-color' : 'lightgreen'}); 
  }); 
});
</script>


</head>
<body> 
   <button type='button' id='btnSubmit' style="background-image:     
    urlbuttonBackground.gif);"       >button</button>
</body>
</html>

Solution

  • You can have these styles defined in a css class and then apply the class on focus and remove it on blur. Try this.

    Remove the inline styling from button

    <button type='button' id='btnSubmit'>button</button>
    

    Css (define the styles as per your need)

    button{
        background: lightgreen;
    }
    .focusBg{
        background: ulr('urlbuttonBackground.gif');
        border: 1px solid red;
    }
    

    JS

    $(document).ready(function() { 
         //Since the button has an id, you can use id selector
         $('#btnSubmit').focus(function(){ 
              $(this).addClass('focusBg');
         }).blur(function(){ 
              $(this).removeClass('focusBg');
         }); 
    });