Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus only one time - Jquery

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>
like image 222
hakkikonu Avatar asked Jul 08 '13 14:07

hakkikonu


2 Answers

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

like image 58
cfs Avatar answered Sep 24 '22 19:09

cfs


You can easily do this using jQuery's .one() function. This only fires the event handler at most once for the element that it is attached to.

You would not need to use $(document).ready(function()... in this case (unless your script comes before your #sharePost element). As an example for you could just do:

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

After the first focus on the element, the handler containing your .animate and .css will never run again. You can go from there if you are wanting is to shrink back down when focus leaves the element.

like image 40
Eric Olson Avatar answered Sep 21 '22 19:09

Eric Olson