Randomize my gallery images

i have a website for using voting actors. i want to randomize my images reloading every time. i wrote this javascript source code for showing my images.

<script type="text/template" id="player-template">

<% _.each(players, function(player) { %>
    <div class='playerWrap'>

        <div id='img'><img src='<?php echo CANVAS; ?>include/view.php?src=<?php echo CANVAS; ?>images/<%= player.player_pic%>&wh=140,161&c=1' /></div>

        <div id='name'><%= player.player_fname%></div>

        <div id='viewinfo'><span class="btn btn-sm" data-toggle="modal" data-playerId="<%= player.player_id%>" data-target="#showPlayerInfo">Details</span></div>


<% }); %>

how to shuffle this code images using JavaScript or PHP. i use this JavaScript code to randomize. but it shows only one image.

    <script type="text/javascript">

  var random = Math.floor(Math.random() * $('.playerWrap').length);


2 answers

  • answered 2018-05-16 05:54 Negi Rox

    use this function to shuffle

    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;
      while (0 !== currentIndex) {
       randomIndex = Math.floor(Math.random() * currentIndex);
       currentIndex -= 1;
       temporaryValue = array[currentIndex];
       array[currentIndex] = array[randomIndex];
       array[randomIndex] = temporaryValue;
     return array;
    var imagearray= [2, 11, 37, 42];//here your object array should be present 
    imagearray= shuffle(imagearray);

  • answered 2018-05-16 06:40 Kalana Mihiranga

    i modify this php code to view images

            $perPage = 6;
            $pageNo = isset($_GET['page']) ? $_GET['page'] : 0;
            $offset = $perPage * $pageNo;
            $topVotedPlayers = $user->getTopVotedPlayers($offset, 20);
            foreach($topVotedPlayers as $topVoted){
                echo "<div class='col-md-4 col-sm-6 col-xs-12'>";
                echo "<div class='playerWrap' id='player_{$topVoted['player_id']}' data-playerId=".$topVoted['player_id'].">";
                echo "<div id='img'><img class='img-responsive' src='".CANVAS."include/view.php?src=".CANVAS."images/{$topVoted['player_pic']}&wh=500,600&c=1' /></div>";
      echo "<div id='name'>{$topVoted['player_fname']} {$topVoted['player_lname']}</div>";
      echo "<div id='sport_name'>{$topVoted['player_desc']}</div>";