views:

47

answers:

2
$('textarea').focus(function() {
    var img = $(this).css('background-image');
    $(this).css('background-image', 'none');
});
$('textarea').blur(function() {
    $(this).css('background-image', img);
});

.. doesn't seem to work. I think somethings wrong, but I can't figure out what.

Many thanks for your help!

+5  A: 

If you define

var img

just inside the .focus() event handler, that variable will not be available within .blur()

So either define var img globaly, or use jQuerys .data() method for instance.

write:

$.data(this, 'img', $(this).css('background-image'));

read:

$.data(this, 'img');

example:

$('textarea').focus(function() {
   var $this = $(this);
   $.data(this, 'img', $this.css('background-image'));
   $this.css('background-image', 'none');
});
$('textarea').blur(function() {
   $(this).css('background-image', $.data(this, 'img') || '');
});
jAndy
+1 - I would just do `$.data(this, 'img')` though, no need to create a wasted object here.
Nick Craver
@Nick: I didn't know that `$.data()` works with DOM objects, too. nice!
jAndy
erm...can you show an example, I can't get it to work. thanks!
Nimbuz
@Nimbuz: added an example.
jAndy
Awesome! Thanks heaps! :)
Nimbuz
A: 

Try to define the url-address for the image in css.

var img = 'images/mybg.png';
$('textarea').blur(function() {
    $(this).css('background-image', 'url('+img+')');
});
hellozimi