0

This is a "Crystals Collector" game which creates four crystals ("divs") with random numbers inside them, which the user clicks to add numbers to a random number the computer has generated, to match the computer's random number. Everything works but I'm having a hard time adding the images of crystals I need into the 4 divs.

var image = "../../assets/images/crystal.jpg"

var crystal = $("<div>");
crystal.attr({
    "class": 'crystal',
    "data-random": randomNum,
    "src": image
});
$(".crystals").append(crystal);

The only result I need is for 4 crystal images to show in my 4 divs created for the random number clicks.

4
  • 1
    you need to create the img tag, set it's src to the image url and then append it to the crystals. Commented Jun 10, 2019 at 18:09
  • 1
    You're creating a <div>. Create an img instead: var crystal = $("<img/>"); Commented Jun 10, 2019 at 18:13
  • Possible duplicate of Adding an img element to a div with javascript Commented Jun 10, 2019 at 18:15
  • Well, I need the 4 <divs> to store the random numbers within. Basically, I need 4 <divs> to store both random numbers AND images within. Commented Jun 10, 2019 at 18:18

2 Answers 2

0

Instead of div create img tag.

var image = "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg"

var crystal = $("<img>");
crystal.attr({
    "class": 'crystal',
    "data-random": 1,
    "src": image,
    "height": '100px',
    "width": '100px'
});

$(".crystals").append(crystal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="crystals"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

Create the image and add to div

var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.