Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery delay() with css()

Tags:

jquery

Why does delay() work here:

$('#tipper').mouseout(function() {
  $('#tip').delay(800).fadeOut(100);
});

But this fails to delay:

$('#tipper').mouseout(function() {
  $('#tip').delay(800).css('display','none');
});

// EDIT - here's a working solution

// EDIT 2 - some bugs fixed

$('#tipper').mouseleave(function() {
  setTimeout( function(){
    $('#tip').css({'display','none'});
       },800);
});
like image 296
jerrygarciuh Avatar asked Mar 22 '11 18:03

jerrygarciuh


People also ask

How to set delay in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

How do you delay a Div load?

$(document). ready(function() { $('#PriceBox'). delay(8000). fadeIn(400); });

What is the use of delay Option?

This option is most valuable in projects where a firm has the exclusive right to invest in a project and becomes less valuable as the barriers to entry decline. There are three cases where the option to delay can make a difference when valuing a firm.


3 Answers

delay() works with the animation (fx) queue. Changing a css property does not work via that mechanism, and thus is not affected by the delay directive.

There is a workaround -- you can inject the property change as a queued operation, like this:

$('#tip')
  .delay(800)
  .queue(function (next) { 
    $(this).css('display', 'none'); 
    next(); 
  });

Also, you should probably be using .hide() instead of .css('display','none').

Here's a working example: http://jsfiddle.net/redler/DgL3m/

like image 100
Ken Redler Avatar answered Oct 02 '22 09:10

Ken Redler


A tiny jQuery extension can help with this. You might call it qcss:

$.fn.extend({
   qcss: function(css) {
      return $(this).queue(function(next) {
         $(this).css(css);
         next();
      });
   }
});

This lets you write:

$('.an_element')
   .delay(750)
   .qcss({ backgroundColor: 'skyblue' })
   .delay(750)
   .qcss({ backgroundColor: 'springgreen' })
   .delay(750)
   .qcss({ backgroundColor: 'pink' })
   .delay(750)
   .qcss({ backgroundColor: 'slategray' })

This can be a reasonably elegant way to define a chained animation. Note that in this very simple form, qcss only supports a single object argument containing CSS properties. (You’d have to do a bit more work to support .qcss('color', 'blue') for instance.)

Here’s an example on jsfiddle.

like image 39
Benji XVI Avatar answered Oct 02 '22 09:10

Benji XVI


Added to Ken Redler's answer / suggestion:

Also, you should probably be using .hide() instead of .css('display','none').

You can do :

$('#tip').delay(800).hide(0);

The 0 is important here. Passing a value to .hide() will implicitly add it to the fx queue and therefore, this will work like expected.

like image 36
jAndy Avatar answered Oct 02 '22 11:10

jAndy