简体   繁体   中英

onfocus & onblur not working in IE

I've wrote some code that will allow me to have some greyed out text on an input form, and when the user focuses on it, the text will disappear and become ungreyed out, if that makes sense...

function editableAlt (elem, colour1, colour2) {
    var elem = document.getElementById(elem);
    elem.onfocus = function () {
        if(this.value == this.defaultValue) {
            this.value = ""; // remove the default text, so the user can enter their own
            this.style.color = "#" + colour1; // change the text colour 
        }
    };
    elem.onblur = function () {
        if(this.value == '') {
            this.value = this.defaultValue; // user left it blank? revert back to the default text
            this.style.color = "#" + colour2; // and change the colour back too
        }
    }
}

This is working on most pages, but on one for some reason the onfocus and onblur aren't working at all - for example if I change it to onclick it triggers no problem.

Is there anything else I can try? :( I am using JQuery, but removing that doesn't seem to effect it at all.

Cheers

I've found that IE is extremely unforgiving when it comes to javascript errors. I ran your code through jslint and got the following errors:


Error: Problem at line 2 character 14: 'elem' is already defined.

var elem = document.getElementById(elem);

Problem at line 10 character 23: Use '===' to compare with ''.

if(this.value == '') {

Problem at line 14 character 6: Missing semicolon.

}

Implied global: document 2


Not trying to skimp on helping your or anything, but I'm guessing if you fix those errors, you'll see more desirable results. Good luck!

What an idiot, sorry guys! I tried removing all other Javascript files, but missed the most important one was it was wrapped in PHP and IE if statements, d'oh!

Suckerfish sfFocus was being applied which caused it to break: http://htmldog.com/articles/suckerfish/shoal/

Sorry :( & many thanks for the suggestions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM