image returns value "null" - javascript

I have a javascript code that points to an image using getElementById. But when I debug it in firebug, it says that my variable has a value of "null". Here is my code:
var image = document.getElementById('myImage');
image.src = "imageone.png";

That's because there is no element with that id.
If the element actually have that id, then the reason is that the element hasn't been parsed yet when the code runs. Put it in the load event to run it after the entire page has been parsed:
window.onload = function() {
var image = document.getElementById('myImage');
image.src = "imageone.png";
};
Alternatively, you can put the script block in the body element, below the image tag.

Related

Javascript: Append and Remove Image from a DIV in setTimeout loop

I'm trying to load an image into a div using JavaScript. Below is the current snippet of the code.
window.onload=function image_show() {
var thumbContainer = document.getElementById("art_img");
var thumbnail = document.createElement("img");
var img_width = document.getElementById("art_img").offsetWidth;
var img_height = document.getElementById("art_img").offsetHeight;
thumbnail.onload=function() {
thumbContainer.appendChild(thumbnail);
}
thumbnail.src = "http://xyz/bkg.png";
thumbnail.width = img_width;
thumbnail.height = img_height;
setTimeout(image_show, 1000 );
}
The appendChild() method keeps appending the images (one below the other) after the Timeout. But I want to actually keep refreshing the div with the same image.
The source of the image will be updated on my website with the same name, and I want the script to display the new image after Timeout. I tried inserting a removeChild() method just before appendChild(), but didn't work as expected. Any help will be appreciated.
just empty the element before you append again
thumbnail.onload=function() {
thumbContainer.innerHTML = ""; // ADD THIS LINE
thumbContainer.appendChild(thumbnail);
}
The problem is that the browser caches the image.
Try appending a timestamp to the src attribute of the thumbnail:
thumbnail.src = "http://xyz/bkg.png?ts=" + Date.now();
This way, the source URL will be slightly different each time the image_show function runs and the picture should be loaded by the browser each time.

Dynamically display an image url with javascript

I am using tag manager to dynamically place information from the website into an html element using custom javascript. My code at the moment is this. PS I can't figure out how to post properly. This actually starts with
function(){
console.log("Start image variable");
var element = document.getElementsByClassName("MagicZoomPlus")[0];
console.log(element);
var image = element.getAttribute("img src").innerHTML;
console.log(image);
return image;
}
This returns the following debug information
unreachable code after return statement[Learn More] trustlogo.js:28:123
Start image variable gtm.js:1:42
<a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus" title="Franklin Paradigm Grey Sofa"> gtm.js:1:136
undefined gtm.js:1:186
The html on the site I am trying to reach is
<a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus" title="Franklin Paradigm Grey Sofa"><img src="/uploads/products/892_3521-05 .jpg" alt="FranklinParadigm Grey Sofa" /></a>
Your .innerHTML() is not needed. The getAttribute() function simply returns a string with the value of the attribute, or null if the attribute is non-existent.
To get the src of your element, therefore, the url of your image, you'd have to do :
var imageSrc = element.getAttribute("src");
and then simply return imageSrc
More info on the mozilla developper network
You could use a selector instead, and also you can access the attribute directly with the dot notation.
If you are trying to target the image within the link:
function(){
var image = document.querySelector(".MagicZoomPlus > img");
// get
console.log(image.src);
// or set the image source
image.src = "https://example.com/hello.jpg";
return image;
}
This is what I ended up coming up with, which works.
function myFunc() {
var img = document.querySelector(".MagicZoomPlus img");
return img.src
}

Is it possible to set the equivalent of a src attribute to the first img src of a page in html and javascript?

I am probably missing something simple but it's quite annoying when everything you read doesn't work.
I am trying to set the "throbber" img src to the first img src of a webpage. So far, I've got:
<script type="text/javascript">
var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src; // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);
Would it be possible to implement this with html only?
And
<div id="throbber"><img src="http://www.cloudaccess.net/images/Google-Chrome-Extensions.jpg" /></div>
Is it possible to change the img src to the first img src of a page depending on the website?
Yes it is. Try following code:
window.onload = function(){
var divEl = document.getElementById('throbber');
var image = divEl.getElementsByTagName('img')[0];
// set the new image
image.src= 'https://your/new/image.png';
}
Note that we need to take advantage of window.onload in order to make sure DOM is ready before manipulating it.
See this JSfiddle DEMO
If your throbber image is in the website from which you're trying to pull the image, you can use jquery like this:
$(function (){
// get the src of the first image that is not your throbber image
var src = $('img:not("#throbber img")').attr('src');
// set the throbber image to this src
$('#throbber img').attr('src', src);
});

determine whether body's background-image (css) has been loaded

Depending on some conditions, different background images are loaded:
$('body').css('background','url(image.png)');
Is there a way to determine whether the background image has loaded? I need to execute a function when the image has been loaded.
You could load the image into a hidden <img> tag and assign an onload handler to the tag. In the onload handler you could populate the background image of the body (which should happen more or less instantly because the image is now in the browser cache) and then run your custom code as well.
var hiddenImg = new Image();
hiddenImg.onload = function(){
$('body').css('background','url(' + this.src + ')');
your_custom_onload_code();
};
hiddenImg.src = 'image.png';
var img = new Image ();
img.onload = function () { $('body').css('background','url(image.png)'); };
img.src = src;

do content added to DOM count for the total page load time?

I mean if I append some contents like this:
<body>
//contents
<script>body.appendChild('<img src="new.png">');
// other contents
</body>
the browser will fire window.onload considering only the original html or it will take in consideration the load of the new image too? (new.png) ?
Besides that code/markup being incorrect, it will consider the new image. To append it to the DOM will be to download whatever the src attribute points to.
However, if this code was placed inside of a window.onload = function() { ... }, then it wouldn't be considered because its download would not occur until your window was loaded.
Here is the code that would actually work...
var img = new Image;
img.src = 'http://www.gravatar.com/avatar/3535689c965d66db3d2a936ced96192a?s=32&d=identicon&r=PG';
img.alt = 'Example';
document.body.appendChild(img);
jsFiddle.

Categories

Resources