Javascript onload event to resize image help - javascript

This might be a simple one for you guys, im learning Javascript and have hit a problem. I am trying to have the script resize a particular image on the page when onload is called like so:
<script type="text/javascript">
function resizeSampleImage()
{
document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.2;
}
</script>
...
<body onload = "resizeSampleImage();" >
...
<img id="sampleImage" src="Images/BP snip.jpg" alt="BuildingPeople.uk.com" />
apologies, forgot to mention that is doesn't work! after loading the page in multiple browsers the image stays it native size and the error consoles say they fail to parsing value for height. Declaration dropped.
I have tried lots of different ways but cannot seem to get it to work.

(document.body.clientWidth) * 0.2 will give you an integer. The CSS height property accepts a length.
Add some units.

There is a live example at http://jsbin.com/uyihe4
You can see the zoom effect when loading. I have only changed the
document.getElementById("sampleImage").style.height
to
document.getElementById("sampleImage").height

Well, your problem is that the images may not be ready when you apply the styles to them.
Use this function instead (note it takes a DOM object):
var imgLoader = function(domImg) {
var imgObj = new Image();
imgObj.onload = function()
{
// apply styles
domImg.style.height = "100px";
}
imgObj.src = domImg.src;
}

Though I haven't figure out the problem. But the following code snippet works for me (Tested in Chrome 8.0 and IE9.0Beta).
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeSampleImage()
{
document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.5;
}
</script>
</head>
<body onload="resizeSampleImage();">
<img id="sampleImage" src="http://news.mydrivers.com/Img/20101217/S03405153.jpg">
</body>
</html>

Related

anyway to check that a img tag is broken or 404'd; without add'l network request

I am using CasperJS to scrape some items, so I can't get on the page early enough to add load and error events on img tags. I would also prefer to not have to do a new XHR request for each image to determine it's validity.
Is there any way to select an image tag and determine if there is an image actually there or if it is not in which the alt text is displayed? JS only, after the page is fully loaded.
This is NOT A DUPLICATE. I am specifically asking if there is a way to do this without another network request. Other questions only have answers that require creating a new image with a new source and thus another network request.
/ Edit
Specifically looking for asserting if am image is loaded after it is complete (document.querySelector('#myImage').complete // returns true:
No new network request (includes creating a new image with a new source)
No onload/onerror events (requires doing so before page is loaded)
Assert that #myImage is broken without the above
I don't know how exactly you would use it , but here is the code snippet from w3schools.
<!DOCTYPE html>
<html>
<body>
<p>This example uses the HTML DOM to assign an "onerror" event to an img element.</p>
<img id="myImg" src="image.gif">
<p id="demo"></p>
<script>
document.getElementById("myImg").onerror = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "The image could not be loaded.";
}
</script>
</body>
</html>
With a bit of working, I was able to find two methods that seem to work:
HTML
<img id="imageA" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
<img id="imageB" src="https://www.google.com/broken.png">
Setup
var imageA = document.querySelector('#imageA');
var imageB = document.querySelector('#imageB');
console.log(imageIsValid(imageA)); // returns true
console.log(imageIsValid(imageB)); // returns false
JavaScript Method 1
function imageIsValid(img) {
return !!img.naturalHeight && !!img.naturalWidth;
}
The natural height and width of broken images will always be 0.
https://jsfiddle.net/2xLsenpp/
JavaScript Method 2
function imageIsValid(img) {
if (img.complete) {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
try {
context.drawImage(img, 0, 0);
return true;
} catch(e) {
return false;
}
}
return false;
}
https://jsfiddle.net/8gdp8nzw/

Rotating logo in html/javascript

im trying to use html and javascript to create a rotating logo on my site.
I want it to rotate on page load, and load them randomly.
Ive tried SO MANY THINGS! that i found on google, and i cant seem to get it to work. Im trying to avoid using php to do it.
i want to be able to have the random image in a tag like below, (if possible)
<img src="" />
So, just to sum it up.
I want to use "html" and "javascript" to create a script that everytime a page is refreshed, it loads a new logo from a directory on my server.
EDIT: what i have tried
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite(myImage)
</script>
You should avoid using document.write. Instead put an id attribute on the img tag, and retrieve it using document.getElementById. You can make it refresh at intervals using the setInterval method:
<img id="logo" />
<script type="text/javascript">
var logos = ["logo1.png", "logo2.png", "logo3.png"];
var currentLogoIndex = 0;
function updateLogo() {
document.getElementById('logo').src = logos[currentLogoIndex];
currentLogoIndex++;
currentLogoIndex %= logos.length;
}
window.setInterval(updateLogo, 1000);
updateLogo();
</script>
you can store the pathes in an array and select them by using random index.
$(document).ready(function() {
var src = ['path1.jpg', 'path2.jpg', 'path3.jpg', 'path4.jpg', 'path5.jpg', 'path6.jpg', 'path7.jpg', 'path8.jpg', 'path9.jpg'];
$('img').attr('src', src[Math.floor(Math.random()*10)]) // it returns a number between 0 and 10
});
You know, there is a jQuery plugin for this which utilizes CSS transformations.
http://www.zachstronaut.com/posts/2009/08/07/jquery-animate-css-rotate-scale.html
I am Resorting to php guys.
<img src="/images/logo/<?php $random = rand(1,3); echo $random; ?>.png" alt="LOGO!!!!" />
works perfectly :)
<html>
<body>
<h1>Random logo From List</h1>
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite("<img src='" + myImage + "' />)
</script>
<h2>Hoo just got a random logo</h2>
</body>
</html>
Looks like this was what you tried for:
For a bit of explanation using document.write and document.getElement:
When you write inline code like above you can use document.write, it will just add the texts just after </h1> like a normal "print" operation.
Once you use it after document is loaded, it clears everything and overwrites whole thing.
If you want to change the document after it is loaded, you have to edit the DOM, the document is represented as DOM after its loaded. In that case you should use different DOM manipulation functions like
document.getElementById('logo-image').src = myImage;

Only load the background-image when it has been fully loaded?

Well, the title pretty much describes my question:
How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded.
I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is?
Best regards,
Aart
........
EDIT:
Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way.
I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome.
I'll just post it here in case anyone else has the same issue:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#img').css('opacity','0').load(function() {
$(this).animate({
opacity: 1
}, 500);
});
});
</script>
<img src='yourimage.jpg' id='img'/>
If the image is included with an img element:
<img src="bg.jpg" id="img" onload="this.style.opacity='1'">
<script>
document.getElementById("img").style.opacity="0";
</script>
That should load the image normally if JavaScript is disabled, but show it only once it loads assuming it's enabled.
One thing to note (that I overlooked): some browsers will not even attempt to load an image if its display property is none. That's why this method uses the opacity attribute.
You can't do it when JS is disabled. However, what you can do is set the background image in CSS and then use the following script (assuming the element has the ID myelem).
(function() {
var elm = document.getElementById('myelem'),
url = 'background image URL here';
elm.style.backgroundImage = "none";
var tmp = new Image();
tmp.onload = function() {
elm.style.backgroundImage = "url('"+url+"')";
// or insert some other special effect code here.
};
tmp.src = url;
})();
EDIT: Although, make sure your background images are optimal. If they are PNG, try having them Indexed with as small a colour table as possible, or make sure the alpha channel is removed if there is no transparency. If they are JPEG, try adjusting the compression.
Check the example on this page:
http://www.w3schools.com/jsref/event_img_onload.asp
Using "image.onload" will start your code only when the image is ready
Without javascript you can't have events, so you won't be able to know if the image is loaded, at least for the first rendering.
You can also use a css preload (put the image as a background in a hidden div), but that would work better in your first refresh and not while loading.
You can set a variable to the image, and when it loads, set it to the body background:
var my_bg = new Image();
my_bg.src = "url(mybackground.png)";
document.style.backgroundImage = my_bg;
What you are looking for is an image onLoad method. If you set the image with a display:none it wont be visible. To get around the possible lack of javascript, you do the following:
<body style="background-image:url(image.png);">
<img src="image.png" style="display:none" onLoad="changeBackground();" />
</body>
<script>
document.body.style.backgroundImage = "";
function changeBackground(){
document.body.style.backgroundImage = "url(image.png)";
}
</script>
This way, if javascript isnt enabled, the bg will load as normal. If it is, it will display at the end

javascript : simple delayed image show

I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.
<html>
<head>
<script type="text/javascript">
function SetTimer()
{
var Timer = setInterval("showImage()",3000);
}
function showImage()
{
document.getElementById('showImage').style.visibility = 'visible';
}
</script>
</head>
<body onLoad="SetTimer()" style="visibility:hidden">
<div id=showImage>
<img src="gwyneth_paltrow_2.jpg">
</div>
</body>
</html>
Am I approaching this incorrectly?
thanks in advance
This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';
getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it. Instead, you should start out as hidden, and then make it appear instead of disappear.
document.getElementById('showImage').style.visibility = 'hidden';
Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
var myImage = new Image();
myImage.src = "gwyneth_paltrow_2.jpg";
document.getElementById("showImage").appendChild(myImage);
}
I'm doing that from memory, so syntax may not be entirely correct.

How does the browser know if an image is loaded?

I need to have a function called after a larger image is loaded on the page. I've tried some various solutions that I've found on here and around the web, but none either fit or work. Here's what I've tried that seems to make the most sense...and this is using jQuery
var imgs = $('#bgStage img.bg'),
imgCnt = imgs.length,
cnt = 0;
imgs.load(function () {
cnt++;
if (imgCnt === cnt) {
homeSlider();
}
}).each(function () {
if (this.complete) {
$(this).trigger('load');
}
});
This doesn't seem to wait until the img.bg is loaded. The homeSlider() function is called and started as I still see the image still loading.
So, I am wondering how a browser determines an image is loaded? Is it when it can read the width and height? Because I am defining the width and height in the CSS for the image to force it to be a certain size.
If anyone has any insight as to what makes the onload event fire for an image, that'd be great! Thanks.
You can always check for $('img').length();
Here's a sample code that should work. I did a project that needed this and I remember that some problems might include:
The browser caches the image (IE i believe) so I had to append ?[random] at the end
Maybe you have to set the src javascriptly so that your event is hooked at the right time
Sample code:
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#imageSample')
.load(function(){
alert($('#imageSample').width());
alert($('#imageSample').height());
})
.attr('src', 'http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg?' + new Date());
});
</script>
<style type="text/css"></style>
</head>
<body>
<img id="imageSample" src="" alt="" />
</body>
</html>
Images might be cached, try this: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
Use something simple like so:
var loaded = false;
var len = $('#bgStage img.bg'), c = 0;
$('#bgStage img.bg').each(function(){
$(this).attr('src',$(this).attr('src') + new Date()); //Remove caching.
$(this).bind('onload',function(){
//Other Stuff here!
if(c == len)
{
HomeSlider();
}
c++; //Increment
});
});
Tell me how it goes :)
Each image has a complete property. Unfortunately not all browsers support it. They always report true, even if the image hasn't loaded at all. IE gets it right. ;-)
http://simon.html5.org/test/html/semantics/img/src/ (not mine)

Categories