0

On page refresh images load randomly. Here images are loading in sequence. I'm trying to load images randomly on page refresh. And I don't want to change the HTML structure. Images are adding through the frontend I can't add in js. Can anyone suggest to me how to achieve.

$(function() {
  $('.randomSlider ul.fader li').hide();
  $('.randomSlider ul.fader li').css('position', 'absolute');
  $('.randomSlider ul.fader li').css('top', '0px');
  $('.randomSlider ul.fader li').css('left', '0px');

  var max = $('.randomSlider ul.fader li').length;

  function showSlider() {

    if (localStorage.slider) {
      $('.randomSlider .fader').find('li:nth(' + localStorage.slider + ')').fadeIn();
      localStorage.slider = parseInt(localStorage.slider, 10) + 1;
      if (localStorage.slider >= max) localStorage.slider = 0;
    } else {
      $('.randomSlider .fader').find('li:nth(0)').fadeIn();
      localStorage.slider = 1;
    }
  }

  showSlider();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="randomSlider">
  <ul class="fader">
    <li data-id="1"><img src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
    <li data-id="2"><img src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
    <li data-id="3"> <img src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
  </ul>
</div>
Husna
  • 1,286
  • 4
  • 19
  • 48

7 Answers7

1

You can put all img src in an array and then generate a random number to get value from array on load

myarray = ["https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg", "https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg", "https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"]
window.onload = function(){
 var randomNum = Math.floor(Math.random() * 3);
 var randomImgSrc = document.getElementById("myRandomImg").src = myarray[randomNum];
 console.log(randomNum)
}
<img src="" id="myRandomImg">
1

For random position of elements on page we can add random item to the beginning of their container n times. Let n be images.length.

Here we change order of <li> elements, not images themselves, so the data-id has to be reordered (if wanted);

document.addEventListener("DOMContentLoaded", () => {
    const li_cont = document.querySelector('.randomSlider .fader');
    const li_items = [...li_cont.querySelectorAll('li')];
    const len = li_items.length;

    for(let i = 0; i < len; i++){
        li_cont.prepend(li_items[Math.floor(Math.random()*len)]);
    }
});
<div class="randomSlider">
    <ul class="fader">
        <li data-id="1"><img src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
        <li data-id="2"><img src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
        <li data-id="3"> <img src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
    </ul>
</div>

Or we can get random order of all images by their num. Then reorder images in list-items. So the list-item order stay same, only images change.

document.addEventListener("DOMContentLoaded", () => {
    const li_cont = document.querySelector('.randomSlider .fader');
    const li_items = li_cont.querySelectorAll('li');
    const images = li_cont.querySelectorAll('img');
    
    reorderImages(getRandomOrder(images.length));

    function getRandomOrder(max){
        const init_arr = [...new Array(max)].map((_,i) => i);
        const result = [];
        while(init_arr.length > 0){
            result.push(...init_arr.splice(Math.floor(Math.random()*(init_arr.length)),1));
        }
        return result;
    }
    
    function reorderImages(order){
        li_items.forEach((li,i) => {
            li.appendChild(images[order[i]]);
        })
    }
});
<div class="randomSlider">
    <ul class="fader">
        <li data-id="1"><img src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
        <li data-id="2"><img src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
        <li data-id="3"> <img src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
    </ul>
</div>

Or we get list of src attributes of images, and reassign them in random order.

document.addEventListener("DOMContentLoaded", () => {
    const images = document.querySelectorAll('.randomSlider img');
    const sources = [...images].map(img => img.getAttribute('src'));
    
    reorderSources(getRandomOrder(images.length));

    function getRandomOrder(max){
        const init_arr = [...new Array(max)].map((_,i) => i);
        const result = [];
        while(init_arr.length > 0){
            result.push(...init_arr.splice(Math.floor(Math.random()*(init_arr.length)),1));
        }
        return result;
    }
    
    function reorderSources(order){
        images.forEach((img,i) => {
            img.setAttribute('src', sources[order[i]]);
        })
    }
});
<div class="randomSlider">
    <ul class="fader">
        <li data-id="1"><img src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
        <li data-id="2"><img src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
        <li data-id="3"> <img src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
    </ul>
</div>
Leonid
  • 766
  • 4
  • 8
1

If you're just trying to randomize the order of the images, not the url, you can detach and sort the li, then append them back to the ul.

$('.fader').append($('.fader li').detach().sort(_=>Math.random()>.5?1:-1));
<div class="randomSlider">
  <ul class="fader">
    <li data-id="1">1<img></li>
    <li data-id="2">2<img></li>
    <li data-id="3">3<img></li>
    <li data-id="4">4<img></li>
    <li data-id="5">5<img></li>
    <li data-id="6">6<img></li>
  </ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10
0

Since you're using jQuery, you should be able to query the child nodes, randomize the order and then replace the nodes with your new result.

See:

So your end result would be something like:

// See https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

// Get children
var target = $("ul.fader");
var imageNodes = target.children();

// Empty parent
target.empty();

// Shuffle nodes
var shuffled = shuffleArray(imageNodes);

// Append shuffled nodes to target element
target.append(shuffled);

You'll want to put all of this above your showSlider(); function.

Haven't had a chance to test this yet, but hope this helps :)

rtimoshenko
  • 884
  • 6
  • 9
0

So u can do this at next way:

$(function() {
 $.fn.shuffle = function() {
    var m = this.length,
      t, i;

    while (m) {
      i = Math.floor(Math.random() * m--);

      t = this[m];
      this[m] = this[i];
      this[i] = t;
    }

    return this;
  };

  $("li").shuffle().each(function(index, data) {
      $(".fader").html("");
      $(".fader").append(data)
  });
});

As u see i create shuffle function to randomize image, after i use loop to get all images, i clear all which u have at page, and append random image from the list.

$(function() {
 $.fn.shuffle = function() {
    var m = this.length,
      t, i;

    while (m) {
      i = Math.floor(Math.random() * m--);

      t = this[m];
      this[m] = this[i];
      this[i] = t;
    }

    return this;
  };

  $("li").shuffle().each(function(index, data) {
            $(".fader").html("");
      $(".fader").append(data)
  });
});


$(function() {
  $('.randomSlider ul.fader li').hide();
  $('.randomSlider ul.fader li').css('position', 'absolute');
  $('.randomSlider ul.fader li').css('top', '0px');
  $('.randomSlider ul.fader li').css('left', '0px');

  var max = $('.randomSlider ul.fader li').length;

  function showSlider() {

    if (localStorage.slider) {
      $('.randomSlider .fader').find('li:nth(' + localStorage.slider + ')').fadeIn();
      localStorage.slider = parseInt(localStorage.slider, 10) + 1;
      if (localStorage.slider >= max) localStorage.slider = 0;
    } else {
      $('.randomSlider .fader').find('li:nth(0)').fadeIn();
      localStorage.slider = 1;
    }
  }

  showSlider();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="randomSlider">
  <ul class="fader">
    <li data-id="1"><img src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
    <li data-id="2"><img src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
    <li data-id="3"> <img src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
  </ul>
</div>

Here working example.

Andrew
  • 572
  • 6
  • 29
0

setInterval(function(){
 var randomNum = Math.floor(Math.random() * 3);
 document.getElementById("demo").className  = "image" +randomNum;
 console.log(randomNum)
},3000)
.image0 {
  left: 0px;
  width: 46px;
  background: url('http://w3schools.com/css/img_navsprites.gif') 0 0;
}

.image1 {
  left: 63px;
  width: 43px;
  background: url('http://w3schools.com/css/img_navsprites.gif') -47px 0;
}

.image2 {
  left: 129px;
  width: 43px;
  background: url('http://w3schools.com/css/img_navsprites.gif') -91px 0;
}
<div id="demo" style="height: 44px;"></div>

Please check my code.

0

Here i add code for get all possible shuffles and store into local storage and shuffles every time with new result until all possibility is close, after that it start with new possibility. This code is lengthy you can minify this but it works better.It gives you new result each and every time. Hope it will help you out.

$(function() {
    var permute = (function() {
        return permute;

        function permute(list) {
            return list.length ?
                list.reduce(permutate, []) : [
                    []
                ];
        }

        function permutate(permutations, item, index, list) {
            return permutations.concat(permute(
                    list.slice(0, index).concat(
                        list.slice(index + 1)))
                .map(concat, [item]));
        }

        function concat(list) {
            return this.concat(list);
        }
    }());
    var currentIndex = [];
    $(".fader li").each(function(index) {
        currentIndex.push($(this).data('id'));
    });
    var originalIndex = localStorage.getItem('originalIndex');
    var possibleIndexing = localStorage.getItem('possibleIndexing');
    if (!originalIndex) {
        localStorage.setItem('originalIndex', currentIndex.toString());
    }
    if (currentIndex.toString() == originalIndex && possibleIndexing) {
        possibleIndexing = JSON.parse(possibleIndexing);
    } else {
        localStorage.setItem('originalIndex', currentIndex.toString());
        permutedData = permute(currentIndex);
        possibleIndexing = permutedData;
        permutedData.map(function(value, index) {
            permutedData[index] = value.toString();
        })
        localStorage.setItem('possibleIndexing', JSON.stringify(permutedData));
    }
    if (possibleIndexing.length <= 0) {
        localStorage.setItem('originalIndex', currentIndex.toString());
        permutedData = permute(currentIndex);
        possibleIndexing = permutedData;
        permutedData.map(function(value, index) {
            permutedData[index] = value.toString();
        })
        localStorage.setItem('possibleIndexing', JSON.stringify(permutedData));
    }

    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    }

    var randomNumber = getRndInteger(0, possibleIndexing.length - 1);

    var currentShuffle = possibleIndexing[randomNumber].split(',');
    counter = 1;
    currentShuffle.map(function(value) {
        $(".fader li[data-id = " + value + "]").data('position', counter++);
    });
    $(".fader li").sort(sort_li).appendTo('.fader');

    function sort_li(a, b) {
        return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
    }

    possibleIndexing.splice(randomNumber, 1);

    if (possibleIndexing.length <= 0) {
        localStorage.setItem('originalIndex', currentIndex.toString());
        permutedData = permute(currentIndex);
        possibleIndexing = permutedData;
        permutedData.map(function(value, index) {
            permutedData[index] = value.toString();
        })
        localStorage.setItem('possibleIndexing', JSON.stringify(permutedData));
    }
    localStorage.setItem('possibleIndexing', JSON.stringify(possibleIndexing));
    $(".randomSlider ul.fader li img").show();
});
<style>
    .randomSlider ul.fader li {
        height: 100px;
    }

    .randomSlider ul.fader li img {
        position: absolute;
        height: 100px;
        display: none;
    }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="randomSlider">
    <ul class="fader">
        <li data-id="1" class="item"><img
                src="https://cdn.pixabay.com/photo/2021/10/03/04/21/woman-6676901_960_720.jpg"></li>
        <li data-id="2" class="item my-element"><img
                src="https://cdn.pixabay.com/photo/2021/08/23/04/02/woman-6566600_960_720.jpg"></li>
        <li data-id="3" class="my-element"> <img
                src="https://cdn.pixabay.com/photo/2020/09/26/14/27/sparrow-5604220_960_720.jpg"></li>
    </ul>
</div>
Dhaval Samani
  • 257
  • 2
  • 5