0

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!

5 Answers 5

3

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>
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@ sjkm Thanks for your response when I try this way I get a broken image link
1
<img src="src" id="Image">

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

1 Comment

@ 7ochem When I try your above code. I get the following error: Unable to get property 'setAttribute' of undefined or null reference. And I'm sure the Id I use in both places is the same!
0
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

Comments

0

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

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.