Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make random dice array return unique attributres / prevent duplicates

Tags:

jquery

i have this dice array that changes attribues(srcset) in grid gallery and i need it to show unique attribues until it runs out and than start again so i wont see 2,3,4 of the same image in grid. Thanks for help

Heres the jQuery:

$(function() {
    //array
    var dice = $('.attachment-lenslight_squares').map(function() {
        return $(this).attr('srcset')
    }).get();

    $('.attachment-lenslight_squares')
        .click(function() {
            var num = Math.floor(Math.random() * dice.length);
            $(this).fadeOut(200, function() {
                $(this).attr('srcset', dice[num]);
            }).fadeIn(200);
        });

    setInterval(function() {
        var rand = Math.floor(Math.random() * 15);
        $('.attachment-lenslight_squares').eq(rand).click();
    }, 3000);

});

Thanks for ideas

like image 485
Martin Sprušanský Avatar asked Dec 03 '25 10:12

Martin Sprušanský


1 Answers

You can swap elements using .not(), destructuring assignment, .html()

var items = $(".items").on("click", "div", function() {
  $(this).fadeOut(200, function() {
    var not = $.map($(".items div").not(this), function(el) {
      return $(el).index(".items div")
    });
    var next = not[Math.floor(Math.random() * not.length)];
    var index = $(this).index(".items div");
    var elems = $(">div", items).toArray();
    [elems[next], elems[index]] = [elems[index], elems[next]];
    items.html(elems).find(this).fadeIn(200)
  });
});

var interval = setInterval(function() {
  items.find("div")
    .eq(Math.floor(Math.random() * items.find("div").length))
    .click()
}, 3000)
.items div {
  width: 25px;
  height: 25px;
  padding: 4px;
  margin: 1px;
  border: 2px solid #000;
  border-radius: 20%;
  text-align: center;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js">
</script>
<div class="items">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>
like image 181
guest271314 Avatar answered Dec 05 '25 01:12

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!