1

I have a function getImgurUrl() and I want what it returns to be the src value of a img tag.

How can I do this?

my function:

function getImgurUrl() {
    //get imgur url for current image
    var cookieArray = document.cookie.split(";");
    var encodedURL = cookieArray[2].split("=");
    var decodedURL = decodeURIComponent(encodedURL[1]);
    return decodedURL;
}

and img tag:

<img id="image" name="image" src=""  alt="If you're seeing this something is wrong.">

2 Answers 2

8
window.onload = function() {
    document.getElementById("image").src = getImgurUrl();
};
Sign up to request clarification or add additional context in comments.

3 Comments

@AClockworkOrange You should look for possible errors with your code in your console and also inspect the active DOM to see if the src was changed to the expected value.
In chrome's Javascript console I'm seeing this "Uncaught TypeError: Cannot set property 'src' of null"
@AClockworkOrange Make sure you only have one element with an id of image!
0
function getImageUrl(imageId) {
  return document[imageId].src;
}

<img id="mike" src="http://yoursite.com/images/1.jpg" />

I haven't tested this but you get the idea.

I'm not sure what you're doing with the cookie logic so just kept example simple.

--

I would recommend you add jQuery to handle cross-browser compatibility as getElementById or others may not work all the time and all versions, also document. might not as well and sometimes it's window.functionName()

In jQuery you would reference the image src similarly but in my return, you'd concat a pound symbol with the id:

return $('#' + id).src;

1 Comment

also, you might have luck in testing using alert(contentHere) to make sure you can get the desired value... for example in your code throw in an alert(document['mike'].src); and if fails try alert(document.getElementById('mike').src); etc. I would recommend you look at jQuery though.

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.