开发者

How do you write jquery to fade out all items of a certain type all the time

So ... I know how to fadeout an item added to the dom (A success/error message in this case), but the way I'm doing it now is by writing the code to fadeout the specific item I need when it is loaded with the DOM, but also writing seperate fadeOut code when the item is added via AJAX.

Is there a more elegant way to handle this? I looked into using the .live() handler but that requires an event be passed in as one of its parameters (not go开发者_JAVA技巧od because I just want the item to fade out after a set amount of time, no matter what).

tldr; I'm trying to write a piece of code that will fadeOut an item whether it loads with the DOM or is added to it (via AJAX for example).


Use the livequery plugin.

$(".fadeOut").livequery(function(){$(this).fadeOut()});


when you add the divs to the dom, assign a class for e.g

<div ...class="your_usual_class fadeout_category other_classes"...>

So now all objects that belong to the fadeout_category can be easily faded with a command

$(".fadeout_category").apply_fadeout;


The most "elegant" solution to your problem would not be to use .live, which listens to a particular DOM node for changes (always use a context for your selector; the callbacks can slow down a complicated page substantially) and then just applies a normal callback assuming the selector conditions are met.

You would want to include the fadeOut with the function that makes the item appear in the first place.

namespace.showMessage = function(message) {
  $('<div class="message">').text(message).appendTo('body').fadeOut(function(){
    $(this).remove();
  });
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜