views:

95

answers:

2

I am trying to right a script for a notification popup. I wan't the popup to fade out after X seconds or fadeout when the user clicks on the message. I can get both effects to work individually but when I try to combine them fadeOut works. This is my code so far:

function notify(data, type) {
 switch(type) {
 case "success":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifySuccess')
  .click(function() {
$("#notify").fadeOut();
  })
  .delay(5000).fadeOut();
break;
 case "error":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifyFailure')
  .click(function() {
$("#notify").fadeOut();
  })
  .delay(5000).fadeOut();
break;
}
}
+1  A: 

You need a .stop() in there to clear the delay out of the queue, like this:

function notify(data, type) {
 switch(type) {
 case "success":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifySuccess')
  .click(function() {
    $("#notify").stop(true, true).fadeOut();
  })
  .delay(5000).fadeOut();
break;
 case "error":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifyFailure')
  .click(function() {
    $("#notify").stop(true, true).fadeOut();
  })
  .delay(5000).fadeOut();
break;
}
}

Also, if you only have success and error for types, you can shorten this down a great deal, like this:

function notify(data, type) {
 $('#notify').html(data)
   .removeAttr("style")
   .addClass(type == 'success' ? 'notifySuccess' : 'notifyFailure')
   .delay(5000).fadeOut()
   .click(function() {
     $(this).stop(true, true).fadeOut();
   });
 }
Nick Craver
+1, mostly for the refactoring :-)
Andy E
Thanks ALOT!!! This did exactly what I wanted. I will cut down the code too as you suggested, again thanks alot!
JClu
A: 

try putting .stop();

.click(function() {
    $("#notify").stop(true,true).fadeOut(); // also in this part, you may change $("#notify") to $(this)
})
Reigel