The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Implementing an SVG Icon System" Nov 30 - 6:00 PM Eastern

jQuery: keypress event should only function once

  • # June 14, 2013 at 10:08 am


    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: 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 will only fire once then.

    # June 16, 2013 at 6:47 am

    This reply has been reported for inappropriate content.

    Try this:

    var once = false;

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

    // Do something on every key press

    if (!once) {
    // Do something only for the first key press
    once = true;

    # June 16, 2013 at 6:58 am

    //Show second input

    # 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

    This reply has been reported for inappropriate content.

    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.

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed