Karl Werner
Karl Werner

Reputation: 51

Javascript delay after click, set timeout not working

Thanks in advance for helping. I am new to JavaScript so i think i'm doing something basic incorrectly. I would like 'toggleclass' between class '.fa' and class '.fa-bars fa-times' to take 1 second after i click on class '.ubermenu-responsive-toggle'

The toggle between '.fa' and '.fa-bar fa times' after clicking on '.ubermenu-responsive-toggle' works. I just can't get the timeset delay down. I keep getting JavaScript errors in Chrome's inspector. I will put my best guess below. I'm sure this is something simple but, like I said, JavaScript is new territory for me.
Thanks again for your help.

jQuery(document).ready(function($) {
   $( '.ubermenu-responsive-toggle' ).on( 'click touchend' , setTimeout(function(){
      jQuery( this ).find( '.fa' ).toggleClass( 'fa-bars fa-times' );
   }, 1000));
});

Upvotes: 0

Views: 867

Answers (3)

Fabian Lurz
Fabian Lurz

Reputation: 2039

Try this

jQuery(document).ready(function ($) {
    $('.ubermenu-responsive-toggle').on('click touchend', function () {
        var that=jQuery(this);
        setTimeout(function () {
            that.find('.fa').toggleClass('fa-bars fa-times');
        }, 1000);
    });
});

Upvotes: 1

guest271314
guest271314

Reputation: 1

Try utilizing .delay() , .queue()

jQuery(document).ready(function($) {
  $(".ubermenu-responsive-toggle").on("click touchend", function(e) {
    jQuery(this).delay(1000, "toggle").queue("toggle", function() {
      jQuery(this).find(".fa").toggleClass("fa-bars fa-times");
    }).dequeue("toggle");
  });
});

jsfiddle http://jsfiddle.net/pLv0n1w4/1/

Upvotes: 1

Jose Mato
Jose Mato

Reputation: 2799

Be carefull with object "this" inside a setTimeout or setInterval function, because maybe could not be the object that you expect, try this:

jQuery(document).ready(function($) { 
    $( '.ubermenu-responsive-toggle' ).on( 'click touchend' , function() {
        var $myToggles = $(this).find( '.fa' );

        setTimeout(function() {
             $myToggles.toggleClass('fa-bars fa-times');
        }, 1000);
    }); 
});

Upvotes: 3

Related Questions