javascript : simple delayed image show - javascript

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.

Related

Change image and Text on Scroll (Javascript)

I dont have much experience in javascript but trying to achieve a slideshow like in https://district2.studio/ where the text and image changes as you scroll. In the example no matter the amount you scroll at a time or inbetween the image changing animation, the image will change only once at a time. I'm trying to achieve this using javascript only and no additional plugin or libraries. Hope someone can help me.
You have some errors.
First of all, you have to wait the DOM is ready. You could movet he entire before de body tag closes to ensure that or use window.onload
class prop elements it's an array.
window.onload = function() {
document.getElementById("image1").onscroll = function() {
if(document.getElementById("image2").classList.contains("scroll")){
document.getElementById("image2").classList.remove("scroll");
} else {
document.getElementById("image2").classList.add("scroll");
}
};
}
Something like this should work

Button onclick doesn't respond

I am fairly new to JavaScript and I am trying to make my own image gallery as my first simple project. I expected it to go smoothly, but it seems like I am doing some trivial mistake, and I have no idea where.
So, my initial plan was: I would set up an image element with empty src property, create an array of image names, add a function that will increase the array pointer by 1 any time it is triggered, and then just add the corresponding value in the array to the src.
It doesn't work, though. Could you please try to see any errors in the code? I really have no idea what to do, just can't find a mistake.
<html>
<body>
<img src="" id="imageCanvas">
<div id="counterDisplay"></div>
<script type="text/javascript">
var images = ["increased.jpg","knight.jpg","knight-g.jpg","golden.jpg","land.jpg"];
var counterDisplay = document.getElementById("counterDisplay");
var imageCanvas = document.getElementById("imageCanvas");
var imageCount = 0;
// function intended to increase the array position indicator by 1, but it always only increases it in relation to the original imageCount value (0), how to make it save the already increased value?
function changeCount() {
imageCount = imageCount+1;
}
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
</script>
// The main problem: it just refuses to respond!
<button onclick="changeCount()">NEXT</button>
</body>
</html>
I didn't debug through this, but my guess is that onclick is being called, but you are not updating the count in that changeCount code.
Try putting almost all the code in changeCount.
function changeCount() {
imageCount = imageCount+1;
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
}
This function runs when the the button is clicked.
function changeCount() {
imageCount = imageCount+1;
}
This code is run when the script first loads.
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
You want it to run when the button is clicked. Move it inside the function.

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 onload event to resize image help

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>

How to use JS to trigger a GIF animation?

I have an animated GIF that plays once (doesn't loop). I would like it to animate when clicked.
I tried something like this:
$('#plus').click(function(){
$('#plus').attr('src','');
$('#plus').attr('src','img/plus.gif')
});
With the hope that quickly resetting the src would trigger the animation, but no luck. Anyone know what would do it?
Try adding the image with a randomly generated querystring so it looks like a new image to the browser.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
$('#plus').click(function(){
$('#plus').attr('src','img/plus.gif?x=' + randomString())
});
</script>
function refreshSrc(who){
return who.src= who.src.split('?')[0]+'?='+(+new Date());
}
refreshSrc(document.images[0])
Tart it up with jQuery syntax, if you like.
This is a bit of an alternative approach.
You could export the individual frames as their own images and handle animation via javascript.
It lets you do a couple of cool things. A colleague recently had a little timer animation that was synced to the configurable slideshow interval in our image gallery.
The other thing you get out of this is you could use pngs and have translucent backgrounds.
There's probably a sprite animation library for javascript out there somewhere :)
Have you tried removing the img tag and adding it back again? (never tried it, just an idea)
You could try having a single-frame image (of the first frame of animation) and show/hide each one on click. If you want it to reset back to the single-frame image when the animation is done, you could use setTimeout (with how long the animation is as the length of time) and have it hide the animation and show the static image.
For those who want to do this when it scrolls into view i did the following.
Link for appear.js : https://github.com/morr/jquery.appear
$('img.large-magnify-glass-animation').appear(function() {
$(this).delay(200, function(){
$(this).attr('src','http://example.com/path/to/gif.gif');
});
});
I just loaded the same gif via the attr('src') upon visiblity after a short delay. No timestamp or random char function. Just used appear plugin.

Categories