views:

3999

answers:

3
+5  Q: 

IE7 input:focus

I have the following CSS which isn't working in IE7.

input:focus{border-width: 2px;border-color: Blue; border-style: solid;}

Basically, I just want to set the border attributes when the input is focused. Works in Firefox etc... If anyone could explain why it isn't working in IE 7 and suggest a possible workaround it would be appreciated. Thanks.

+8  A: 

A known answer for this problem is using the following code:

    sfFocus = function() {
    var sfEls = document.getElementsByTagName("INPUT");
    for (var i=0; i<sfEls.length; i++) {
     sfEls[i].onfocus=function() {
      this.className+=" sffocus";
     }
     sfEls[i].onblur=function() {
      this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
     }
    }}
if (window.attachEvent) window.attachEvent("onload", sfFocus);

And here is the css style

input:focus, input.sffocus{background-color:#DEEFFF;}

The problem is that IE doesn't recognise that style at all.

EDIT: You can find a solution using prototype here: http://codesnippets.joyent.com/posts/show/1837

nandokakimoto
Thanks for confirming it as a problem. I'm using jquery, so I can implement the code using javascript if I need to. I would rather not do that though because my page is rather saturated with events already. I'm hoping for a css solution or hack that would work.
Rob
@Rob Schieber, since you're using jQuery, you can do a quick addition at page load, checking if you're dealing with MSIE, and add events for focus and blur with the same kind of idea that nandokakimoto is using. It does require a small change to your CSS as well. Check my answer for another approach.
artlung
+8  A: 

I understand the desire to not add events, but in this case it looks like MSIE7 is jerk on this point and needs to be hacked around. In your comment to @Ape-inago you indicate you're using jQuery. Here's a solution in jQuery. I tested this in MSIE 6 and 7, and it appears to do what you want.

<script type="text/javascript">
$(document).ready(function(){
    if (jQuery.browser.msie === true) {
     jQuery('input')
      .bind('focus', function() {
       $(this).addClass('ieFocusHack');
      }).bind('blur', function() {
       $(this).removeClass('ieFocusHack');
      });
    }

});
</script>
<style>
input:focus, input.ieFocusHack
{
    border-width: 2px;
    border-color: Blue;
    border-style: solid;
}
</style>
artlung
I can't vote you up due to some buggy behavior in SO but this does work, thanks for the answer.
James McMahon
+1  A: 

it ALMOST works

The problem with this is that when the element in question has focus and you open another window and then return to the page with the element in question on it, it is styled incorrectly :(

Dan Lewis