22

I am trying to display image, through JavaScript, but i can't figure out how to do that. I have following

function image(a,b,c)
{
  this.link=a;
  this.alt=b;
  this.thumb=c;
}

function show_image()
{
  document.write("img src="+this.link+">");
}

image1=new image("img/img1.jpg","dsfdsfdsfds","thumb/img3");

in HTML

<p><input type="button" value="Vytvor" onclick="show_image()" > </p>

I can't figure out where should I put something like image1.show_image();.

HTML? Or somewhere else...

Brett DeWoody
  • 55,478
  • 28
  • 131
  • 182
ivanz
  • 743
  • 2
  • 11
  • 31

1 Answers1

52

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

dash
  • 87,236
  • 4
  • 50
  • 71
jessegavin
  • 70,879
  • 26
  • 136
  • 164
  • 2
    The fiddle shows a button with the name 'Add Google Logo'. When pressed, the text 'Google Logo' is added to the right. No image is visible. I checked the existence of the logo.gif image & got a 404 error. When I changed it to an existing address (https://www.pinterest.at/pin/340655159306311689/), it did the same again. Tested with Google Chrome version 60.0.3112.113 (official build) (64-bit) – Sae1962 Sep 15 '17 at 08:03
  • You are correct @Sae1962 when I wrote this over 6 years ago I sort of knew that at some point the url would probably return 404 – jessegavin Sep 15 '17 at 15:13
  • :-D The problem is not with you, but with stackoverflow that does not has a coherent page that includes ALL stuff about a question but relies on other pages. – Sae1962 Sep 18 '17 at 06:11
  • Thankfully in this situation it's pretty easy to "get" the concept even if the image is broken. – jessegavin Sep 18 '17 at 19:22