Search code examples
jqueryfocusbackgroundtextarea

Clear background if content present in textarea (jQuery)


Please see this jsFiddle: https://jsfiddle.net/Wmq6f/

I have a textarea that has a background image, it is removed on 'focus' and restored on 'blur' but when the content is present in the textarea it should not show in either case, but I can't achieve that with this jQuery:

$('textarea').focus(function() {
   var $this = $(this);
   $.data(this, 'img', $this.css('background-image'));
   $this.css('background-image', 'none');
});
$('textarea').blur(function() {
    if($.trim($('textarea').val()).length){
         $this.css('background-image', 'none');
    } else {
        $(this).css('background-image', $.data(this, 'img'));
    }
});

Thanks for your help


Solution

  • The textarea tag isn't closed which can be a source of some annoyance :)

    Also it might be helpful to factor out the logic from focus and blur callbacks into a separate function as the same checks need to happen on both events.

    1. if textarea is empty, show image
    2. otherwise hide image

    Another advantage of factoring this logic out in a separate function is that you can call this new function onload, which will initialize the textarea before any focus or blur event happen.

    On jsfiddle, when you choose the "onLoad" option on the left, the JavaScript code is automatically wrapped in a window.load callback, so you don't have to specify it in code. Either that or choose the "No wrap" option to write the window.load event in code yourself.

    Fiddle update:

    function init(text) {
        text = $(text);
        text.data('img', text.css('background'));
        
        var update = function() {
            if(text.val() == '') {
                text.css('background', text.data('img'));
            }
            else {
                text.css('background', 'none');
            }
        };
    
        text.focus(update);
        text.blur(update);
    
        update();
    }
    
    init('textarea');
    
    ​