Focus only one time - Jquery
Asked Answered
E

2

5

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>
Estradiol answered 8/7, 2013 at 14:43 Comment(0)
D
9

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

Duplicity answered 8/7, 2013 at 14:53 Comment(0)
C
2

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.

Composer answered 8/7, 2013 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.