user2363025
user2363025

Reputation: 6505

specify image source in javascript

I was wondering is there a way to only specify the source of an image in javascript. So if I had the following image tag:

<img class="CustomerPict" id="Image" alt="name" src=src style="left: 18px; top: 18.5px;">

And in javascript I want to declare the variable src? Any help would be appreciated!

Upvotes: 0

Views: 138

Answers (5)

Andreas Louv
Andreas Louv

Reputation: 47099

You can make it a oneliner by using the img-tags onerror attribute:

<img src='not-found.zzz' onerror='this.src=window.src;'>

But make sure that the specified image in window.src (global scope) is correct or the script will loop forever...


 <!DOCTYPE html>
 <html>
 <head>
     <meta charset='UTF-8'>
     <script type='text/javascript'>
         var src = 'my_real_image.png';
     </script>
 </head>
 <body>
     <img src='not-found.zzz' onerror='this.src=window.src;'>
 </body>
 </html>

DEMO: http://jsbin.com/ozimov/1/embed

Upvotes: 0

7ochem
7ochem

Reputation: 2340

<img src="src" id="Image">

document.getElementById('Image').setAttribute('src', 'http://www.gravatar.com/avatar/c9bef77e2d810012d8c96f84b9fc9bc9?s=32&d=identicon&r=PG');

Upvotes: 1

JFakult
JFakult

Reputation: 347

img=document.getElementById("Image");
console.log(img.src);

or the nicer way (in my opinion)

img=document.getElementsByTagName("img");
console.log(img[0].src);

then you can assign img[0].src a value

Upvotes: 0

Quentin
Quentin

Reputation: 943569

HTML provides no way to set an attribute value using JavaScript.

You either need to set the src to a default value (possible a 1x1 transparent gif) and then change it with JavaScript later, or to generate the entire img element from JS.

<img class="CustomerPict" id="Image" alt="name" src="1x1.gif" style="left: 18px; top: 18.5px;">
<script>
    document.getElementById('Image').src = src;
</script>

or

<script>
    var container = document.getElementById('image-container');

    var image = document.createElement('img');
    image.src = src;
    image.id = "Image";
    image.className = "CustomerPict";
    image.alt = "name";
    // You can move these to a style sheet ruleset with a class or id selector
    image.style.left = "18px";
    image.style.top = "18.5px";

    container.appendChild(image);
</script>

Upvotes: 3

sjkm
sjkm

Reputation: 3937

document.getElementById('Image').src = 'http://domain.com/picture.png';

Upvotes: 2

Related Questions