Focus only one time - Jquery

hakiko picture hakiko · Jul 8, 2013 · Viewed 8k times · Source

hi friends i have a textarea and i want to use animate() and css() functions with this element.

css() function is working properly but the problem is focus() func. After page load everything is fine,

when i focus to textarea its height is incrementing 50px but when I blur and then focus again to textarea then height incrementing 50px again.

I don't want to use blur() function.

My question is about using focus() function. I want to use focus() one time per page load.

<script>
              $(document).ready(function(){
                  $("#sharePost").focus(function(){
                  $(this).animate({height:"+=50px"});
                  $(this).css("background-color","#ffccdd");
                  });
                  $("#sharePost").blur(function(){
                  //$(this).animate({height:"-=50px"});
                  });
              });
</script>

Answer

cfs picture cfs · Jul 8, 2013

To fire an event just once, you can use the one() function, which attaches an event listener then removes it after the first time it's fired:

$(document).ready(function(){
    $("#sharePost").one('focus', function(){
        $(this).animate({height:"+=50px"});
        $(this).css("background-color","#ffccdd");
    });

});

Working Demo