views:

35

answers:

4

I have the script

<input type="text" name="name" value="Joe Bloggs" onfocus="this.value=''"/>

Just like I am doing with the onfocus="this.value…" can I change the background of the field (+ change other things?)

Many thanks.

Also, does anyone have a better idea of how to do the script above, but so that the text reappears when the deselect it.?

Many thanks again.

A: 

On your event, append the class name...

el.className+= 'test'

then set a background on that class in your css.

meder
regex replace? Say wha?
William Hand
have you considered using jQuery? Would be much easier for you to do dom manipulation.
meder
+1  A: 
frabjousB
+1  A: 

Something along the lines of

onfocus="this.value=''; this.style.backgroundColor='#f00'" onblur="this.style.backgroundColor='white'"

will get approximately what you want done simply, although it would also be possible for it to interact badly with presentation defined elsewhere and as such is probably rather crude to be considered a best practise.

Alternatively, you could as suggested add / remove a specific class to the element onfocus / onblur. At this point I would also second the jQuery recommendation: although it's hardly necessary just for this, you will find that it makes life with Javascript in general much more pleasant.

If you use jQuery, something like

$('input').focus(function() { $(this).addClass('focus') });
$('input').blur(function() { $(this).removeClass('focus') });

would allow you to cleanly define the appearance of focussed inputs in CSS. Consult jQuery documentation for the surrounding context necessary to make this work.

PeterT
+2  A: 

It's considered best practice to leave styling to CSS and logic to JS.

You can do this in css using the :focus pseudo-class. (http://www.quirksmode.org/css/focus.html) Unfortunately, it doesn't work in IE7 or lower. For those browsers, you can use javascript to add a class to the <input> to do the same thing.

CSS

input:focus, input.focus {background:#ff0}

If you are using jQuery, here is how you would do that.

$('input').focus(function(){
     $(this).addClass('focus');
});
$('input').blur(function(){
     $(this).removeClass('focus');
});
washwithcare
Where would I have to put the jQuery on the page? Sorry, I am a bit of a novice to jQuery.
William Hand
You would put it in the `<head>` of your document.`<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>`
washwithcare