-2

I have this code that is creating to div after clicking on button. But its not working... here is the html with script in it

<img id="boxm" style="position: fixed;left: 90%;padding-top:2%" 
src="images/box1.png" id="image1" onclick="diffImage(this);myFunction();" />
<script>
function myFunction()
{
document.getElementById("surprise").createElement="<img 
style="width:304px;height:228px"
src='images/mese.png' />";
}
</script>

<div id="surprise">

</div>
3
  • You have to escape double quote from img element. Commented Oct 14, 2017 at 6:39
  • Document has a createElement method, Element doesn't. Commented Oct 14, 2017 at 6:46
  • possible duplicate stackoverflow.com/questions/7802744/… Commented Oct 14, 2017 at 6:57

3 Answers 3

1
<img src='images/box1.png' onclick="showSurpriseImage()" />
<div id="surprise">
    Surprise Image will be displayed here
</div>
<script>
function showSurpriseImage() {
    var x = document.createElement("IMG");
    x.setAttribute("src", "images/mese.png");
    x.setAttribute("width", "304");
    x.setAttribute("height", "228");
    x.setAttribute("alt", "surprise image");

    document.getElementById("surprise").appendChild(x);
}
</script>

Best Practice to set attributes checkout here

Hope this helps

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

2 Comments

Thank you, how would you do random TOP and LEFT position? I tried to do this var randomY = Math.round(Math.random() * availH) + 'px'; var randomX = Math.round(Math.random() * availW) + 'px'; x.style.left = randomX; x.style.top = randomY;
Code remain same. depends on the availH and availW before that do console the randomX and randomY check what it returns
0

<img id="boxm" 
src="http://wfarm1.dataknet.com/static/resources/icons/set28/7f8535d7.png" id="image1" onclick="myFunction();" />
<script>
function myFunction() {
    var s = document.getElementById("surprise")
    var x = document.createElement("IMG");
    x.setAttribute("src", "http://wfarm1.dataknet.com/static/resources/icons/set28/7f8535d7.png");
    s.appendChild(x);
}
</script>

<div id="surprise">

</div>

Comments

-1

Try this :

function myFunction()
{
document.getElementById("surprise").innerHTML='<img style="width:304px;height:228px" src="images/mese.png" />';
}

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.