hakki
hakki

Reputation: 6521

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>

Upvotes: 5

Views: 9316

Answers (2)

Eric Olson
Eric Olson

Reputation: 2985

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.

Upvotes: 2

colestrode
colestrode

Reputation: 10658

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

Upvotes: 9

Related Questions