开发者

In jquery Set a delay to fade out or fadeout right away on click

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).f开发者_JS百科adeOut();
break;
 case "error":
  $('#notify').html(data)
  .removeAttr("style")
  .addClass('notifyFailure')
  .click(function() {
$("#notify").fadeOut();
  })
  .delay(5000).fadeOut();
break;
}
}


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();
   });
 }


try putting .stop();

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜