MintY
MintY

Reputation: 643

onclick add image to div

I am trying to get image in a <div> using onclick.

Now I am getting the text on click. but I want to get the image in div on click...

How can i do this...?

Here is code I have implemented,,

Code:

<script>
function myFunction()
{
document.getElementById("surprise").innerHTML=images/aftersurprise.png;
}
</script>

When I click on element I should get the aftersurprise.png image on surprise element...

Upvotes: 2

Views: 42531

Answers (7)

chillu
chillu

Reputation: 1

$('#divname').append or prepend("<img src='pathOfImages.jpg'/>");

here use only one attributes like append , another prepend >(before content)

Upvotes: 0

Ahsan Khalid Butt
Ahsan Khalid Butt

Reputation: 1

As I understand, your issue is that all the content is displayed on a new/ existing page except image...! If that is so, you just need to put some delay when calling your JS function. Try this:

function Myfunction () 
{
    setTimeout(load, 1000); //this delay will allow browser to load complete image
    function load() 
    {
       var divToPrint = document.getElementById('surprise');
       var popupWin = window.open('', '_blank','width=1000, height=800, location=no, left=200px');
       //popupWin.document.open(); //needed when popup required
       popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
       popupWin.document.close();
    }  
}

Upvotes: 0

nrsharma
nrsharma

Reputation: 2572

You are giving the image url to the innerHTML of div element. To add an image there you have to do something like this

document.getElementById("surprise").innerHTML="<img src='images/aftersurprise.png' />";

Or why are you not going with jquery, it's very easy with that like

$('#surprise').append("<img src='images/aftersurprise.png' />");

Upvotes: 2

Arasan
Arasan

Reputation: 137

img = document.createElement("img");

img.setAttribute('src','https://www.google.co.in/images/srpr/logo11w.png');

document.getElementById("surprise").appendChild(img);

here u can set ur image src

Upvotes: 0

user2672373
user2672373

Reputation:

Try this

(function() {
    var oDiv = document.getElementById('surprise');
    oDiv.addEventListener('click', function() {
        this.setAttribute('style', 'background-image: images/aftersurprise.png');
    }, false);
})();

It sets the image as background image of the div

Upvotes: 0

Praveen
Praveen

Reputation: 56549

Just giving the image url will not add the image inside the div. You have to specify it using img tag.

or dynamically create it using the following code and append to the div

var img = document.createElement('img')
img.src = 'images/aftersurprise.png';
document.getElementById('surprise').appendChild(img);

Upvotes: 0

Pankaj Sharma
Pankaj Sharma

Reputation: 1853

use

document.getElementById("surprise").innerHTML="<img src='images/aftersurprise.png' />";

Upvotes: 10

Related Questions