Grow your CSS skills. Land your dream job.

jQuery: keypress event should only function once

  • # June 14, 2013 at 10:08 am

    Hi,

    I’m using a keypress event on a input type=text. When someone is starting to type the keypress is started and will put a textarea into the document. But it should only do this ones. Now it does it with every key that is pressed. So I get as many textarea’s with every letter I’m typing of my sentence.

    # June 14, 2013 at 10:21 am

    We’d need to see a link but it sound to me as though your jQuery is not specific enough in it’s targeting.

    # June 14, 2013 at 4:25 pm

    If you go to: http://popaquestion.com/kaj/ and start typing, then you will see.

    # June 14, 2013 at 5:22 pm

    Not sure what you are trying to do… but you could remove the event listener in the event callback, but everything inside http://popaquestion.com/kaj/js/animatie.js will only fire once then.

    # June 16, 2013 at 6:47 am

    Try this:

    var once = false;

    $('input').keypress(function() {

    // Do something on every key press
    console.log('ok');

    if (!once) {
    // Do something only for the first key press
    $('#foo').append('<textarea></textarea>');
    once = true;
    }

    });
    # June 16, 2013 at 6:58 am

    $(‘input’).bind(‘keyup’,function(event){
    //Show second input
    $(this).unbind(event);
    });

    # June 17, 2013 at 2:36 am

    Thanks guys, will try these methods today!

    # June 17, 2013 at 4:57 am

    I used the solution of @Hompimpa. It works. Thanks. I’m just starting with learning jQuery.

    # December 18, 2014 at 8:50 am

    I used following
    if($($(this)).val().length ==1),Because I am lazy

    # December 18, 2014 at 10:57 am

    If I am not mistaken (how coincidental that my previous post in another topic was also about this), the cleanest solution would be this :

    $('input').one('keypress', function() {
    

    Flipping a ‘switch’ works just as well of course.
    Never mind it’s a year and a half late.

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".