ivanz
ivanz

Reputation: 805

How to display image with JavaScript?

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...

Upvotes: 23

Views: 366970

Answers (2)

Hecanet
Hecanet

Reputation: 431

Thank you... I made small modifications/simplifications. Works as intended.

HTML: Add Image

Javascript:

function addLogo() { var src = "https://i.gifer.com/origin/93/935d72c7bc35828ea93b5898691f28fd_w200.gif"; show_image(src, 124,124, "My Image"); }

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

Upvotes: 0

jessegavin
jessegavin

Reputation: 75640

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/

Upvotes: 55

Related Questions