سؤال

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>
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top