Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add a click event and disable the click event after the click

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #165659
    gowda24
    Participant
    <div id="ClickTxt" class="">
         <input type="text" name="admin" value=""/>
        
    </div>
    
    $(document).ready(function(){
        $('#ClickTxt').on('click',function(){
                $(this).css('background-color','#f5f5f5');
         });
    
    });

    How can we unbind the click event after the click.

    #165663
    Paulie_D
    Member

    Simplest way would be to give give the element an one-time class initially and remove/toggle it as part of part of your function.

    #165806
    noahgelman
    Participant
    $(document).ready(function(){
        $('#ClickTxt').on('click',function(){
                $(this).css('background-color','#f5f5f5').unbind('click');
         });
    
    });
    
    #166532
    Taufik Nurrohman
    Participant
    $(document).ready(function(){
        $('#ClickTxt').on('click',function() {
            if ($(this).hasClass('clicked') return; // Disable click function if element has a class "clicked"
            $(this).addClass('clicked') // Add a "clicked" class on click
                .css('background-color','#f5f5f5').off('click');
        });
    });
    
    #167430
    Podders
    Participant

    If your using .on() then just call .off() inside the click event handler

    $(document).ready(function(){
        $('#ClickTxt').on('click',function(){
                $(this).css('background-color','#f5f5f5').off();
         });
    });
    #167438
    Paulie_D
    Member

    Could you not just use .one ?

    http://api.jquery.com/one/

    #167521
    dyr
    Participant

    We put a click in your click so you can click while you click..

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.