Random Background at the Ready - javascript

This is really simple, but I'm not a programmer. I just brute force code with general problem solving skills. It's not workin' for this. This code is set to randomize the background image, and it works. However, it's set to wait until the page loads completely, so its timing is too inconsistent. As I understand it, document.ready would give me more consistent (and quicker) timing with it, but I can't seem to make it work. Here's the working version:
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = [
"http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg",
"http://static.tumblr.com/0obftwk/Xmym8xfet/artmuseumarea.jpg",
"http://static.tumblr.com/0obftwk/znNm8xf9e/rowhouseswestphilly.jpg",
"http://static.tumblr.com/0obftwk/af1m8xf87/phillyvista.jpg",
"http://static.tumblr.com/0obftwk/ydIm8xf74/chinagatephiladelphia.jpg",
"http://static.tumblr.com/0obftwk/8kCm8xf41/broadritner.jpg"
];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>

If the list of images is known before you load the page, stick the references to your image in the CSS, and then just change the className on document.body
.bgClass1 {background-image: url(http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg)}
... and so on...
<body class="bgClass1">
Otherwise, build a preloader with js

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

What are some ways to speed up an img swap in jquery / javascript?

I have a slightly vague question. I have the following in my code: http://jsfiddle.net/PMnmw/2/
In the jsfiddle example, it runs smoothly. The images are swapped quickly and without any hassle. When it is in my codebase though, there is a definite lag.
I'm trying to figure out why that lag is happening. The structure of the jquery is exactly the same as above. I.e. Inside the $(document).ready (...) function, I have a check to see if the user clicked on the img (based on the classname) and then I execute the same code as in the jsfiddle.
I'm at my wits end trying to figure out what to do here... Clearly I'm not doing the swap right, or I'm being very heavy handed in doing it. Prior to this, one of my colleagues was using AJAX to do the swap, but that seems to be even more heavy duty (a full fledged get request to get the other icon...).
I've modified your fiddle: http://jsfiddle.net/PMnmw/12/
Things I've optimized:
Created a variable for both img1 and img2, so that you won't have to navigate the DOM to reference those two images anymore, thusly improving performance.
Applied a click handler to the images themselves, so you don't have to search the children of the wrapper.
The basic idea was to reduce the number of jquery selections as much as possible.
Let me know if this helped speed things up.
$(document).ready(function() {
var img1 = $('#img1');
var img2 = $('#img2');
$(".toggle_img").click(function(e) {
var target = $(e.target);
if(target.is(img1)){
img1.hide();
img2.show();
}
else if (target.is(img2)) {
img2.hide();
img1.show();
}
});
});
Images that are not visible are normally not loaded by the browser before they are made visible. If there seems to be a problem, start by downloading an image optimizer like RIOT or pngCrush to optimize your images.
If it's only two arrows, you should consider joining them into a CSS sprite.
You could try not doing everything with jQuery, but it shouldn't really make that much difference.
Something like this maybe, with the hidden image loaded in JS and some traversing done outside jQuery (but that is probably not the problem, although the code seems overly long for a simple image swap?) :
$(document).ready(function() {
var img=new Image();
img.src='http://i.imgur.com/ZFSRC.png'; //hidden image url
$(".wrapper").click(function(e) {
if(e.target.className=='toggle_img') {
$('.toggle_img').toggle();
if (e.target.parentNode.childNodes[1].style.display=='none') {
console.log("hello");
} else {
console.log("goodbye");
}
}
});
});
FIDDLE
​

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