Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the selected images same as randomindex selected from array in javascript

I have an array notes having nine jpg's on it, and an array items nine label and nine url's on it.

this code has three boxes It selected 3 items randomly from an array items.

I have placed the randomly selected item's label inside 3 boxes, inside <P> tags, and corresponding image on background from array items

I have stored currosponding images of notes on randomIndex selection to array notesselected this is called to box002 img src

Class box002 can be dragged and dropped to the corresponding number in four boxes displayed. then blue digit and background in box dissappears.

I have a working code now

My problem is that I want the box002 item should be same as the box digit, now drop is form left side box onwards

ie if box002 digit is 2 the drop(leftmost box) should be blue 2 number with background url image2

how to change my code to make this happen.

    var array2 = [];
    var items = [{
        label: '1',
        url: 'https://via.placeholder.com/150x150.jpg?text=image1'
      },
      {
        label: '2',
        url: 'https://via.placeholder.com/150x150.jpg?text=image2'
      },
      {
        label: '3',
        url: 'https://via.placeholder.com/150x150.jpg?text=image3'
      },
      {
        label: '4',
        url: 'https://via.placeholder.com/150x150.jpg?text=image4'
      },
      {
        label: '5',
        url: 'https://via.placeholder.com/150x150.jpg?text=image5'
      },
      {
        label: '6',
        url: 'https://via.placeholder.com/150x150.jpg?text=image6'
      },
      {
        label: '7',
        url: 'https://via.placeholder.com/150x150.jpg?text=image7'
      },
      {
        label: '8',
        url: 'https://via.placeholder.com/150x150.jpg?text=image8'
      },
      {
        label: '9',
        url: 'https://via.placeholder.com/150x150.jpg?text=image9'
      }
    ];

    var notes = ['https://via.placeholder.com/75x75?text=1',
      'https://via.placeholder.com/75x75?text=2',
      'https://via.placeholder.com/75x75?text=3',
      'https://via.placeholder.com/75x75?text=4',                                                                                                              'https://via.placeholder.com/75x75?text=5',
      'https://via.placeholder.com/75x75?text=6',
      'https://via.placeholder.com/75x75?text=7',
      'https://via.placeholder.com/75x75?text=8',
      'https://via.placeholder.com/75x75?text=9'
    ];


    var tempimages = [];
    var notesselected = [];


    array2 = items.slice();

    var item;

    function rvalue() {

      ptags = document.querySelectorAll('[name="values"]');
      boxtags = document.getElementsByClassName("box");


    for (var index = 0; index < 3; index++) {
    randomIndex = Math.floor(Math.random() *array2.length)

    item = array2[randomIndex];
    array2.splice(randomIndex, 1);

    try {
    ptags[index].style.visibility = "visible";
    ptags[index].textContent = item.label;
    ptags[index].dataset.itemIndex = randomIndex;

    tempimages.push({data: item,index: randomIndex
    });
    notesselected.push({data: notes[randomIndex],
    index: randomIndex});

    boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
    } catch (err) {
    console.log('Exception');
    }

      }

    var tlen = tempimages.length;
    }


    function displayAllImages() {
    try {
    if (tempimages.length == 0) {
    rvalue();
    }

    var arr2 = notesselected;
    item = arr2.shift();

    image = document.getElementById('slide');
        //image.src = "images/"+item.data.url;
    image.src = item.data;
    image.dataset.itemIndex = item.index;
    } catch (err) {
    console.log(err.message);
    }
    };

    $(function() {
    displayAllImages();
    });

    function allowDrop(ev) {
    ev.preventDefault();
    }

    function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
    }

    function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    var el = document.getElementById(data);

    var x = document.getElementById("slide").dataset.itemIndex;
    var y = ev.target.dataset.itemIndex;


    if (x == y) {
    ev.currentTarget.style.backgroundColor = 'initial';
    ev.currentTarget.style.backgroundImage = 'initial';
    ev.currentTarget.style.border = 'initial';
    var pParagraph = ev.currentTarget.firstElementChild;

    pParagraph.style.visibility = "hidden";

    item = this.item;
    var arrayvalue = item.dataindex;

    tempimages.splice(arrayvalue, 1);

    if (tempimages.length == 0)
    {
    rvalue();
    }
    displayAllImages();
      } 
    else {
    alert("WRONG PLACED");
    }
    }
    body {
      overflow: hidden;
    }

    .box {
      width: calc(10.3% - 4px);
      display: inline-block;
      border-radius: 5px;
      border: 2px solid #333;
      border: #000 border-color: #e6e600;
      margin: -2px;
      border-radius: 0%;
      background-color: #99ffff;
    }

    .box {
      height: 15vh;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background-size: contain;
    }

    .box002 {
      position: absolute;
      top: 10.3vh;
      left: 40.98vw;
      cursor: pointer;
    }

    .box002 img {
      width: 14.0vw;
      height: 23.0vh;
      border-radius: 50%;
    }

    p {
      font: "Courier New", Courier, monospace;
      font-size: 30px;
      color: rgba(0, 0, 0, 0.6);
      text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
      color: #005ce6;
      text-align: center;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container2">
      <div class="containerr">
        <div class="pic" id="content">


    <div id="container">

    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
       <p name="values"></p>
    </div>
    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
       <p name="values"></p>
    </div>
    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
       <p name="values"></p>
    </div>
          </div>
        </div>
      </div>
    </div>

    <div class="box002" draggable="true" ondragstart="drag(event)" id="2">
      <img src="" draggable="true" id="slide" border="rounded" />
    </div>
like image 304
Jupiter Avatar asked Oct 30 '18 04:10

Jupiter


1 Answers

I think you have many things going wrong here:

  1. Using index is a wrong idea, you can use the label as the key as you have unique item for each object.
  2. Your displayAllImages returns wrong iterations, I have applied proper filter to display the random image from the available tempImages.

Things you need to take care of:

  1. Assign proper levels
  2. You can possibly use 1 array instead of 2 notes, items.

Here is the demo to resolve your problem to display the image right from the available items randomly.

I have added comments to the code, so you can check the changes.

var array2 = [];
var items = [{
        label: '1',
        url: 'https://via.placeholder.com/150x150.jpg?text=image1'
    },
    {
        label: '2',
        url: 'https://via.placeholder.com/150x150.jpg?text=image2'
    },
    {
        label: '3',
        url: 'https://via.placeholder.com/150x150.jpg?text=image3'
    },
    {
        label: '4',
        url: 'https://via.placeholder.com/150x150.jpg?text=image4'
    },
    {
        label: '5',
        url: 'https://via.placeholder.com/150x150.jpg?text=image5'
    },
    {
        label: '6',
        url: 'https://via.placeholder.com/150x150.jpg?text=image6'
    },
    {
        label: '7',
        url: 'https://via.placeholder.com/150x150.jpg?text=image7'
    },
    {
        label: '8',
        url: 'https://via.placeholder.com/150x150.jpg?text=image8'
    },
    {
        label: '9',
        url: 'https://via.placeholder.com/150x150.jpg?text=image9'
    }
    
];

var notes = ['https://via.placeholder.com/75x75?text=1',
    'https://via.placeholder.com/75x75?text=2',
    'https://via.placeholder.com/75x75?text=3',
    'https://via.placeholder.com/75x75?text=4', 'https://via.placeholder.com/75x75?text=5',
    'https://via.placeholder.com/75x75?text=6',
    'https://via.placeholder.com/75x75?text=7',
    'https://via.placeholder.com/75x75?text=8',
    'https://via.placeholder.com/75x75?text=9'
];


var tempimages = [];
var notesselected = [];


array2 = items.slice();

var item;

function rvalue() {

    ptags = document.querySelectorAll('[name="values"]');
    boxtags = document.getElementsByClassName("box");
    //if array length is 0 then we need to identify the game as completed
    if (array2.length === 0) {
        alert('Game completed');        
        return;

    }

    for (var index = 0; index < 3; index++) {
        randomIndex = Math.floor(Math.random() * array2.length)

        item = array2[randomIndex];
        array2.splice(randomIndex, 1);

        try {
            ptags[index].style.visibility = "visible";
            ptags[index].textContent = item.label;
            ptags[index].dataset.itemLabel = item.label;

            //using label as an identity
            tempimages.push({
                data: item,
                label: item.label
            });
            notesselected.push({
                data: item.url,
                label: item.label
            });

            boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
        } catch (err) {
            console.log('Exception');
        }

    }

    var tlen = tempimages.length;
}


function displayAllImages() {
    try {
    
        if (tempimages.length == 0) {
            rvalue();
        }
        
        if(tempimages.length === 0){
         image = document.getElementById('slide');
         image.style.display = 'none';
         return;
        }

        // getting random item from the available items
        var arr2 = tempimages;
        item = arr2[Math.floor(Math.random() * arr2.length)]        

        image = document.getElementById('slide');
        //getting notes item
        var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
        image.src = dataURL;
        image.dataset.itemLabel = item.label;

    } catch (err) {
        console.log(err.message);
    }
};

$(function() {
    displayAllImages();
});

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {

    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");


    var x = document.getElementById("slide").dataset.itemLabel;
    var y = ev.target.dataset.itemLabel;
    //add improvisation box drag is valid
    if(ev.target.tagName === "DIV"){
       y =  ev.target.children[0].dataset.itemLabel;
    }
    


    if (x == y) {
        ev.currentTarget.style.backgroundColor = 'initial';
        ev.currentTarget.style.backgroundImage = 'initial';
        ev.currentTarget.style.border = 'initial';
        var pParagraph = ev.currentTarget.firstElementChild;

        pParagraph.style.visibility = "hidden";

        item = this.item;
        tempimages = tempimages.filter(a => a.label !== item.label);

        if (tempimages.length == 0) {
            rvalue();
        }
        displayAllImages();
    } else {
        alert("WRONG PLACED");
    }
}
body {
      overflow: hidden;
    }

    .box {
      width: calc(10.3% - 4px);
      display: inline-block;
      border-radius: 5px;
      border: 2px solid #333;
      border: #000 border-color: #e6e600;
      margin: -2px;
      border-radius: 0%;
      background-color: #99ffff;
    }

    .box {
      height: 15vh;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background-size: contain;
    }

    .box002 {
      position: absolute;
      top: 10.3vh;
      left: 40.98vw;
      cursor: pointer;
    }

    .box002 img {
      width: 14.0vw;
      height: 23.0vh;
      border-radius: 50%;
    }

    p {
      font: "Courier New", Courier, monospace;
      font-size: 30px;
      color: rgba(0, 0, 0, 0.6);
      text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
      color: #005ce6;
      text-align: center;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container2">
      <div class="containerr">
        <div class="pic" id="content">


    <div id="container">

    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
       <p name="values"></p>
    </div>
    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
       <p name="values"></p>
    </div>
    <div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
       <p name="values"></p>
    </div>
          </div>
        </div>
      </div>
    </div>

    <div class="box002" draggable="true" ondragstart="drag(event)" id="2">
      <img src="" draggable="true" id="slide" border="rounded" />
    </div>
like image 173
Just code Avatar answered Sep 28 '22 03:09

Just code