Setting img tag's src as the result of a javascript function

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

Answers


window.onload = function() {
    document.getElementById("image").src = getImgurUrl();
};

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;

Need Your Help

How to use MongoDB find() to perform range queries on numeric strings?

python mongodb

How can I make a find() in MongoDB, using find to be >= with some value, but that value is a numeric string?

my submit form doesn't send in first time but send in second time when submit button click

javascript jquery form-submit

I have a form that I check its values with ajax and if valid then send to another page here is my index.js