I need some suggestions and ideas to improve a background image rotator.
The script as of now is very basic but I'm looking to change 2 thing.
I want the images to fade into each other.
I need to be able to preload the images so it doesn't have the delay when loading them when they first display.
Thoughts?
<script type="text/javascript">
var images = ['bg1.png', 'bg2.png', 'bg3.png'];
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(images/' + images[curImage] + ')'
}
window.setInterval(switchImage, 5000);
</script>
Example: http://www.nickersonweb.com/demo/PMS/index.html
For fading, try fadeOut() and fadeIn() with jQuery. (Demo and documentation here: http://api.jquery.com/fadeOut/, http://api.jquery.com/fadeIn/)
For preloading, trying making an invisible image somewhere on the page, like this:
<img src='bg1.png' width="0" height="0">
Another way to preload the images is using javascript to create an image object. Here's the code I used for something similiar.
var imgnum=0;
var imgsrcs=new Array("imgs/img1.jpg","imgs/img2.jpg")
var fimgs=new Array();
var imgid="imgid";
function timedCount()
{
$("#"+imgid).fadeTo(1000,0,function(){newimage();
});
setTimeout(timedCount,5000);
}
function newimage()
{
imgnum=(imgnum+1)%imgsrcs.length;
document.getElementById(imgid).src=fimgs[imgnum].src;
$("#"+imgid).fadeTo(1000,1);
}
function initializeslideshow()
{
var i;
for(i=0;i<imgsrcs.length;i++)
{
fimgs[i]=new Image(270,270)
fimgs[i].src=imgsrcs[i];
}
}
initializeslideshow();
setTimeout(timedCount,5000);
You'll need to link to jQuery (and jQuery UI, I think) to use the code above, like this, for instance:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>
Related
I don't think I explained this properly, but I ended up answering my own question, basically I was looking remove the head code because it made the document look ugly and was very tedious everytime when it came to scrolling, I put the head javascript code into it's file and removed the code from index head section and it seems to be working just fine.
Thanks all for the help!
/close
/answered
Can anybody point towards an easier method to load random images on my index.html page?
This is the current method I'm using
In the head section:
// It currently goes to css/images/images/410.png, I have just put six here so it isn't long and annoying
<script type="text/javascript">
var imageURLs = [
"css/images/avatars/1.png"
, "css/images/avatars/2.jpg"
, "css/images/avatars/3.png"
, "css/images/avatars/4.png"
, "css/images/avatars/5.png"
, "css/images/avatars/6.png"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"Oh no, the image is broken!\"/>';
return img;
}
</script>
In the body section:
<!-- RANDOM IMAGE 1 -->
<script type="text/javascript">
document.write(getImageTag());
</script>
<!-- RANDOM IMAGE 2 -->
<script type="text/javascript">
document.write(getImageTag());
</script>
I currently have 410 images altogether so you can image how annoying it is within the head section code
If your images are all named like that, this should work:
<script type="text/javascript">
var imagesCount = 410;
function getImageTag() {
var img = '<img src=\"css/images/avatars/';
var randomIndex = 1+Math.floor(Math.random() * imagesCount );
img += randomIndex;
img += '.png\" alt=\"Oh no, the image is broken!\"/>';
return img;
}
</script>
I've got the following script which swaps the source of an image. However currently this happens after the page loads so the user experiences a split second of seeing one picture before it switches to the correct image.
<script>
window.onload = function () {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
};
</script>
How can I get the image to switch before loading?
Note I've also tried:
<script>
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
});
</script>
but this results in the same thing occurring
Both of the window.onload or jQuery's $(function()... functions are only called when the page is fully loaded.
The closest you could get is to add the function to the images onload handler.
<img src="..." onload="function() {...}">
But I suspect the same will still occur.
If the image's src needs to be set using javascript then you could try dynamically creating the image and adding it in where you need it, using something like the following.
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
var imgElement = $('<img>').attr("src", "/Content/Images/" + winnerName + ".jpg");
$("#pictureDiv").append(imgElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pictureDiv"></div>
I have a JavaScript function to display images in a slideshow by changing the source. I have tried to create smth to include a fadeIn effect but I think it was catastrophic..Here is my JavaScript function. I don't need a complete answer, just some tips helping me to achieve that. I'm a very beginner in JavaScript but I want to learn it well. If there is a way to do that without jQuery, it would be nice, or to include jQuery directly inside this function will be the best.
{
function nextImage() {
if (currentImage < 5) {
currentImage = currentImage + 1;
} else {
currentImage = 1;
}
document.getElementById('image').src = 'images/' + currentImage + '.jpg';
}
}
Naturally, what the fadein will be adapt as a fadeout in the opposite function, but I think this example can help a newbie like me.
with jquery it would go something like this:
function nextImage() {
if (currentImage < 5) {
currentImage = currentImage + 1;
} else {
currentImage = 1;
}
$("#image").fadeOut('fast', function() {
$("#image").attr('src','images/' + currentImage + '.jpg');
$("#image").fadeIn('fast');
});
}
I don't think it's a stupid question, though for whatever reason my own questions get downvoted, go figure! (end rant)
You might consider if you are able to use CSS there are CSS3 fade transitions that you can try.
If you were to do it in Javascript I would probably use jQuery to do it because those functions are already there and all you have to do is use .show('slow') and .hide('slow') and that argument 'slow' will automatically do the animation for you.
http://api.jquery.com/show/
Otherwise if you want to write it from scratch, then you can probably look at the jQuery source code to see how the actual animation effect is done.
You should JQuery as they have made it very easy to do the effects:
http://api.jquery.com/category/effects/fading/
Take a look at their examples and documentations
Here is an example:
Examples:
Example: Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
<style>
span { color:red; cursor:pointer; }
div { margin:3px; width:80px; display:none;
height:80px; float:left; }
div#one { background:#f00; }
div#two { background:#0f0; }
div#three { background:#00f; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>Click here...</span>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script>
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
</script>
Some tips on how to start using JQuery:
var a = $(document); // <-- set the hole document to variable a
var b = $("#myid"); // <-- set the element that has id="myid" to variable b
var c = $(".myclass"); // <-- set the element(s) that has class="myclass" to variable c
var d = $("img"); // <-- set the img element(s) to variable d
Use Chrome Web Inspector or Firebug to debug your JavaScript code
as the title says I'm trying to figure out how to call this javascript function in my webpage. It's for my business, and the template is just a basic, free one. I'm sure for someone more experienced than me it's probably just a simple matter of formatting it correctly. Here's what I'm working with.
Code that goes in the HEAD portion of the webpage:
var theImages = new Array()
theImages[0] = 'splash1.jpg'
theImages[1] = 'splash2.jpg'
theImages[2] = 'splash3.jpg'
theImages[3] = 'splash4.jpg'
theImages[4] = 'splash5.jpg'
theImages[5] = 'splash6.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}
</script>
Now to call the function I use:
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
Here's the page in which I'm trying to implement it:
http://coloradopp.com/index4.html
Instead of just displaying an image, I would like to call that function. Splash 1-6 are all the same size as the original image.
Here's the code snippet:
<div id="splash">
<img class="pic" src="images/splash1.jpg" width="870" height="374" alt="" />
</div>
As you can tell the page calls on a style sheet (style.css) for all the formatting.
Can anyone offer any tips on how to make this work? From what I've gathered, one cannot implement javascript into css sheets. Thanks in advance.
Do something like this:
showImage() {
var theImages = [ 'splash1.jpg', 'splash2.jpg', 'splash3.jpg', 'splash4.jpg', 'splash4.jpg' ];
var img = theImages[Math.round(Math.random() * (theImages.length - 1))];
document.getElementById('splash').innerHTML = '<img src="' + img + '">');
}
First move your javascript code inside the function something like:
function showImage(){ ...your code goes here...}
And then you can initiate the function on page load like this:
<body onload="showImage()">
You can set the images dynamically as background-image and place something like this
<script>
document.write('<style>#splash{ background-image:url(\'images/splash'+Math.round(Math.random()*5+1)+'.jpg\');}</style>');
</script>
at the head of your page. With this solution you have to set fix dimensions for your div tag (870x374)
I'm working on making a JS script that will go in the header div and display a few pictures. I looked into JQuery Cycle, but it was out of my league. The code I wrote below freezes the browser, should I be using the for loop with the timer var?
<script type="text/JavaScript" language="JavaScript">
var timer;
for (timer = 0; timer < 11; timer++) {
if (timer = 0) {
document.write('<img src="images/one.png">');
}
if (timer = 5) {
document.write('<img src="images/two.png">');
}
if (timer = 10) {
document.write('<img src="images/three.png">');
}
}
</script>
Thanks!
Assuming you want a script to rotate images and not just write them to the page as your code will do, you can use something like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="target"></div>
<script>
var ary = ["images/one.png","images/two.png","images/three.png"];
var target = document.getElementById("target");
setInterval(function(){
target.innerHTML = "<img src=\""+ary[0]+"\" />";
ary.push(ary.shift());
},2000);
</script>
</body>
</html>
Of course the above code has no effects (like fading) which jQuery will give yous, but it also doesn't require loading the entire jQuery library for something so basic.
How about just running the script after the page loads?
<script>
// in <head> //
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
}
</script>
Then use <body onload="load();"> to run the script.
Edit
To add in a delay loading images, I rewrote the code:
<script>
// in <head> //
var displayOnLoad = true; // Set to true to load the first image when the script runs, otherwise set to false to delay before loading the first image
var delay = 2.5; // seconds to delay between loading images
function loadImage(url) {
image = document.createElement("img");
image.src = images[i];
headDiv.appendChild(image);
}
function load() {
var headDiv = document.getElementById("head");
var images = ["images/one.png", "images/two.png"];
for(var i = 0; i<images.length; i++) {
setTimeout(loadImage(images[i]), (i+displayOnLoad)*(delay*1000));
}
}
</script>
Set displayOnLoad = false; if you want to wait the specified delay before loading the first image. The delay is set in seconds. I recommend waiting over a single second between images, as they may take some time to download (depending on the user's internet speed).
As with the first snippet, I haven't tested the code, so please tell me if an error occurs, and I will take a look.
Since you used the jquery tag on your question, I assume you are OK with using jQuery. In which case, you can do something like this:
In your static HTML, include the img tag and set its id to something (in my example, it's set to myImg) and set its src attribute to the first image, e.g.:
<img id="myImg" src="images/one.png">
Next, use jQuery to delay execution of your script until the page has finished loading, then use setTimeout to create a further delay so that the user can actually spend a few seconds looking at the image before it changes:
<script>
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
$(function() {
// Document is ready
setTimeout(function() {
// We will get here after the first timer expires.
// Change the image src property of the existing img element.
$("#myImg").prop("src", "images/two.png");
setTimeout(function() {
// We will get here after the second, nested, timer expires.
// Again, change the image src property of the existing img element.
$("#myImg").prop("src", "images/three.png");
}, imgTimeoutMsecs);
}, imgTimeoutMsecs);
});
</script>
Of course, that approach doesn't scale very well, so if you are using more than three images total, you want to modify the approach to something like this:
var imgTimeoutMsecs = 5000; // Five seconds between image cycles
// Array of img src attributes.
var images = [
"images/one.png",
"images/two.png",
"images/three.png",
"images/four.png",
"images/five.png",
];
// Index into images array.
var iCurrentImage = 0;
function cycleImage() {
// Increment to the next image, or wrap around.
if (iCurrentImage >= images.length) {
iCurrentImage = 0;
}
else {
iCurrentImage += 1;
}
$("#myImg").prop("src", images[iCurrentImage]);
// Reset the timer.
setTimeout(cycleImages, imgTimeoutMsecs);
}
$(function() {
// Document is ready.
// Cycle images for as long as the page is loaded.
setTimeout(cycleImages, imgTimeoutMsecs);
});
There are many improvements that can be made to that example. For instance, you could slightly simplify this code by using setInterval instead of setTimer.
The code you've provided simply iterates through the for loop, writing the images to the browser as it does so. I suggest you take a look at JavaScript setTimeout function.
JS Timing