JQuery - hide a set of divs/images one by one randomly
I have a set of visible divs/or images. by clicking one item, I'd like to hide the other divs/images. But it should be
- randomly - one by one with either fadeOut() out or hide(). - (maybe animated)My HTML:
<DIV class="myDivBox">Box no 1</DIV>
<DIV class="myDivBox">Box no 2</DIV>
<DIV class="myDivBox">Box no 3</DIV>
<DIV class="myDivBox">Box no 4</DIV>
<DIV class="myDivBox">Box no 5</DIV>
<DIV class="myDivBox">Box no 6</DIV>
<DIV class="myDivBox">Box no 7</DIV>
<DIV class="myDivBox">Box no 8</DIV>
<DIV class="myDivBox">Box no 9</DIV>
<DIV class="myDivBox">Box no 10</DIV>
<DIV class="myDivBox">Box no 11</DIV>
<DIV class="myDivBox">Box no 12</DIV>
My Code so far:
$(document).ready(function(){
// I know, this will hide all items of class .itembox
$(".item_box").click(function (event)
{
$(".item_box").random().fadeOut(); // using a random class to hide
});
});
I am using the random plugin available at github:
(function($)
{
jQuery.fn.random = function(num) {
num = parseInt(num);
if (num > this.length) return this.pushStack(this);
if (! num || num < 1) num = 1;
var to_take = new Array();
this.each(function(i) { to_take.push(i); });
var to_keep = new Array();
var invert = num > (this.length / 2);
if (invert) num = this.length - num;
for (; num > 0; num--) {
for (var i = parseInt(Math.random() * to_take.length开发者_如何学Python); i > 0; i--)
to_take.push(to_take.shift());
to_keep.push(to_take.shift());
}
if (invert) to_keep = to_take;
return this.filter(function(i) { return $.inArray(i, to_keep) != -1; });
};
}) (jQuery);
Is there a way I can have this even without the random plugin? Thanks
This will randomly hide one of the visible boxes when you click the item_box
element:
$(function(){
$(".item_box").click(function() {
var $visible = $(".myDivBox:visible");
$visible.eq(Math.floor(Math.random() * $visible.length)).hide('slow');
});
});
This will hide all boxes at randomly chosen times within five seconds:
$(function(){
$(".item_box").click(function() {
$(".myDivBox").each(function(i, e){
window.setTimeout(function() {
$(e).hide('slow');
}, Math.random() * 5000);
});
});
});
精彩评论