Get the items in an array in sequence then repeat? - javascript

<img src="link" id="hof" </div>
<span id="myspan">Compliment: </span>
<script type="text/javascript">
function change() {
// ---------- Caption and images !! -----------//
var things = ["Slide01", "Slide04", "Slide05", "Slide06"];
var captions = ["Very nice", "Awesome", "Cool", "Best"];
// ^^^^^^^^^^ Captions and Images !! ^^^^^^^^^^ //
var image = document.getElementById('hof');
var thing = things[];
image.src = "link" + thing + ".jpg"; // change the image
span = document.getElementById("myspan");
span.innerText= "Compliment: " + captions[]; //change caption
}
setInterval('change()', 4000);
</script>
So i am new to javascript i am trying to make a slideshow with captions but i need the values in the array to display in sequence like (slide01>slide02>slide03) then repeat from the start when it reaches the last value.

To answer what you actually asked: You'd use an index variable defined outside change. Start with 0 and (after rendering the slide) increment it, wrapping around when you get to things.length. There's a trick for that last part:
index = (index + 1) % things.length;
Other notes:
Don't use parallel arrays, use an array of objects.
var slides = [
{name: "Slide01", caption: "Very Nice"},
// ...
];
then
var slide = slides[index];
image.src = "link" + slide.name + ".jpg";
span.innerText = "Compliment: " + slide.caption + ".jpg";
Define that array outside change, there's no need to re-create it every time change is called.
Don't pass strings into setInterval or setTimeout; pass in the function instead:
setInterval(change, 4000);
Consider wrapping all of your code in a scoping function so index, the array of slides, and the change function aren't globals:
(function() {
// ...your code here...
})();

<body onload="imgcarousel()">
<img src="" id="hof">
<p id="caption"></p>
<button onclick="imgcarousel()">Next</button>
</body>
<script>
var count = 0;
var things = ['Slide01', 'Slide04', 'Slide05', 'Slide06'] ;
var captions = ['Very Nice','Awesome','Cool','Best'];
function imgcarousel()
{
count++;
var img = document.getElementById("hof");
var caption = document.getElementById("caption");
if(count >= things.length)
{
count = 0;
}
img.src = things[count]+".png";
caption.innerHTML = "Compliments: " +captions[count];
}
</script>

Related

Random images load without repeat

Hi I found a script which loads images one after another into my div element. Everything works fine, but I would like it to load random images which do not repeat in a circle of all images.length.
Since I'm a total newb in this I tried to do something but most of the time I am able to load random images but without repeat check.
If you can, please help.
Thank you all in advance!
<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
i = 0;
}, 5000);
});
</script>
You can use the shuffle method explained on the answer below.
How can I shuffle an array?
And get the first element on your array
image.css('background-image', 'url(' + images[0] + ')');
You may find a issue on this method, when the same image get loaded after shuffle the array. In this case, I recommend you to store in a variable the name of the last image shown, and before the array get shuffled, just test if the first element is equal the last image.
var lastImageLoaded ='';
setInterval(function() {
shuffle(images);
var imageUrl = images[0];
if(lastImageLoaded !== ''){ // Handle the first load
while(lastImageLoaded === images[0]){
shuffle(images);
}
}
lastImageLoaded = image;
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + imageUrl + ')');
image.fadeIn(1500);
});
Here is a complete object that takes in an array of image urls, and then displays them randomly until it has shown them all. The comments should be pretty explanatory, but feel free to ask questions if I didn't explain something enough. Here is a fiddle
//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
//holds the array that is passed in
var images;
// new shuffled array
var displayImages;
// The parent container that will hold the image
var image = $("#imageContainer");
// The template image element in the DOM
var displayImg = $(".displayImg");
var interval = null;
//Initialize the rotator. Show the first image then set our interval
function init(imgArr) {
images = imgArr;
// pass in our array and shuffle it randomly. Store this globally so
// that we can access it in the future
displayImages = shuffle(images);
// Grab our last item, and remove it
var firstImage = displayImages.pop();
displayImage(firstImage);
// Remove old image, and show the new one
interval = setInterval(resetAndShow, 5000);
}
// If there are any images left in our shuffled image array then grab the one at the end and remove it.
// If there is an image present in the Dom, then fade out clear our image
// container and show the new image
function resetAndShow() {
// If there are images left in shuffled array...
if (displayImages.length != 0) {
var newImage = displayImages.pop();
if (image.find("#currentImg")) {
$("#currentImg").fadeOut(1500, function() {
// Empty the image container so we don't have multiple images
image.empty();
displayImage(newImage);
});
}
} else {
// If there are no images left in the array then stop executing our interval.
clearInterval(interval);
}
}
// Show the image that has been passed. Set the id so that we can clear it in the future.
function displayImage(newImage) {
//Grab the image template from the DOM. NOTE: this could be stored in the code as well.
var newImg = displayImg;
newImg.attr("src", newImage);
image.append(newImg);
newImg.attr("id", "currentImg");
newImg.fadeIn(1500);
}
// Randomly shuffle an array
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
return {
init: init
}
});
var imgArr = [
"https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
"https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg",
"https://i.ytimg.com/vi/icqDxNab3Do/maxresdefault.jpg",
"http://www.funny-animalpictures.com/media/content/items/images/funnycats0017_O.jpg",
"https://i.ytimg.com/vi/OxgKvRvNd5o/maxresdefault.jpg"
]
// Create a new Rotator object
var imageRotator = ImageRotator();
imageRotator.init(imgArr);
you can try to make and array filled with 0's
var points = new Array(0,0,0, 0)
//each one representing the state of each image
//and after that you make the random thing
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
while (points[i]!=1){
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
}
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
points[i]=1;
image.fadeIn(1500);
});

JavaScript: set background image with size and no-repeat from random image in folder

I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .

Need to set styling rules to a JavaScript image randomizing script

I am trying to set the background images to be fixed and be stretched to fit the screen. the js that i am using if to switch the backgroud image on every pageload
Head
<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>
Body
<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>
The js itsself works fine to randomize the images but is currently set to 1 image
Simple, change both scripts to:
<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
, 'http://tinyurl.com/nqw2t9b'
, 'http://tinyurl.com/nkogvoq'
// , 'url 4'
]
, image = images[ (Math.random() * images.length)|0 ]
; //end vars
window.onload=function(){
document.body.style.background=
"url('"+image+"') no-repeat center center fixed";
document.body.style.backgroundSize=
"cover"; // width% height% | cover | contain
};
</script>
Nothing more to configure, just add/remove/change urls.
Example fiddle here.
Hope this helps.
inum needs to be set to something other than 1. You can set it to the number of images in the array.
Also, arrays start with index 0, so to be safer, you should index your array accordingly.
<script language="JavaScript">
// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";
...
images[4] = "lastImage.jpg";
// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];
// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
// set inum
var inum = images.length;
var randnum = Math.random();
var randIndex = Math.floor(randnum * inum);
// Ensure you have an array item for every image you are using.
var imageFile;
if (randIndex < images.length) {
imageFile = images[randIndex];
}
...
</script>
In the body
<script type="text/javascript">
window.onload = function() {
if (imageFile) {
var body = document.getElementsByTagName("body")[0];
if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
}
}
</script>

webGL story sphere popups

I am trying to adapt the really cool looking WebGL Story Sphere, source code and css here. There's one big problem: once you click on a news article, the text of the article in the popup is always the same. I want to modify the code so that when you click on an article, the right text appears in the popup.
I'm working from a set of article texts that I specify in the code, e.g. var captions = ["good","better","best"]. Though the article titles and images populate correctly in the popup, I can't get the text to do so. Can you help me?? Here's what I've got:
// function code
var passvar = null; // failed attempt to store texts for later
function initialize() {
math = tdl.math;
fast = tdl.fast;
canvas = document.getElementById("canvas");
g_fpsTimer = new tdl.fps.FPSTimer();
hack();
canvas.addEventListener("mousedown", handleMouseDown, false);
canvas.addEventListener("mousemove", handleMouseMove, false);
canvas.addEventListener("mouseup", handleMouseUp, false);
// Create a canvas 2d for making textures with text.
g_canvas2d = document.createElement('canvas');
window.two2w = window.two2h = g_tilesize;
g_canvas2d.width = two2w;
g_canvas2d.height = two2h;
g_ctx2d = g_canvas2d.getContext("2d");
window.gl = wu.create3DContext(canvas);
if (g_debug) {
gl = wd.makeDebugContext(gl, undefined, LogGLCall);
}
//gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, gl.TRUE);
// Here is where I specify article titles, images, captions
// Titles and images populate the popup correctly, captions don't...
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
var headlines = titles.concat( titles);
var blurbs = captions.concat( captions);
var tmpImages = [];
var tmpHeadlines = [];
var tmpCaptions = [];
// make a bunch of textures.
for (var ii = 0; ii < g_imagesDownGrid; ++ii) {
var textures = [];
for (var jj = 0; jj < g_imagesAcrossGrid; ++jj) {
var imgTexture = new ImgTexture();
textures.push(imgTexture);
if (tmpImages.length == 0) {
tmpImages = images.slice();
}
if (tmpHeadlines.length == 0) {
tmpHeadlines = headlines.slice();
}
if (tmpCaptions.length == 0) {
tmpCaptions = blurbs.slice();
}
var rando = math.randomInt(tmpImages.length);
var img = tmpImages.splice(rando, 1)[0];
var headline = tmpHeadlines.splice(rando, 1)[0];
var caption = tmpCaptions.splice(rando, 1)[0];
passvar = caption;
if (img.indexOf('videoplay.jpg') > -1){
window.vidtexture = imgTexture;
images = images.slice(1); // dont use that thumb again.
headlines = 'WebGL Brings Video To the Party as Well'
}
imgTexture.load(img, /* "[" + jj + "/" + ii + "]" + */ headline);
}
g_textures.push(textures);
}
// And here's where I try to put this in a popup, finally
// But passvar, the stored article text, never refreshes!!!
<div id="story" class="prettybox" style="display:none">
<img class="close" src="imagesphere/assets/close.png">
<div id="storyinner">
<input id = "mytext">
<script>document.getElementById("mytext").value = passvar;</script>
</div>
</div>
And here is my click handler code:
function sphereClick(e){
window.console && console.log('click!', e, e.timeStamp);
var selected = g_textures[sel.y][sel.x];
window.selected = selected;
animateGL('eyeRadius', glProp('eyeRadius'), 4, 500);
var wwidth = $(window).width(),
wheight = $(window).height(),
story = $('#story').width( ~~(wwidth / 7 * 4) ).height( ~~(wheight / 6 * 5) ),
width = story.width(),
height = story.height(),
miniwidth = 30;
story.detach()
.find('#storyinner').find('h3,img,caption').remove().end().end()
.show();
story.css({
left : e.pageX,
top : e.pageY,
marginLeft : - width / 2,
marginTop : - height / 2
}).appendTo($body); // we remove and put back on the DOM to reset it to the correct position.
$('style.anim.story').remove();
$('<style class="anim story">')
.text( '.storyopen #story { left : ' + (wwidth / 3 * 2) + 'px !important; top : ' + wheight / 2 + 'px !important; }' )
.appendTo($body);
$(selected.img).prependTo('#storyinner').parent();
$('<h3>').text(selected.msg.replace(/\(.*/,'')).prependTo('#storyinner');
$body.addClass('storyopen');
} // eo sphereClick()
There's a lot wrong here, but here's a start. It won't solve your problem, but it will help you avoid issues like this.
var passvar = null; is a global variable.
Your loop for (var ii = 0; ... sets that global variable to a new value on every iteration.
Later, you click something and the global variable passvar is never changed.
If you want to use this pattern, you need to set passvar from your click handler so it has the value that was clicked. Since you didn't actually post your click handlers, it's hard to advise more.
But this is also a bad pattern, functions take arguments for a good reason. Since you have to find your clicked item in the click handler anyway, why not pass it directly which does involve a shared global variable at all?
var handleMouseUp = function(event) {
var story = findClickedThing(event);
if (obj) {
showPopup(story.texture, story.caption);
}
}
Which brings me to this:
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
When you have 3 arrays, all of the same length, each array describing a different property of an object, you are doing it wrong. What you want, is one array of objects instead.
var stories = [
{
title: "a",
caption: "good",
image: "imagesphere/assets/1.jpg"
}, {
title: "b",
caption: "better",
image: "imagesphere/assets/bp/2.jpg"
}, {
title: "c",
caption: "best",
image: "imagesphere/assets/bp/3.jpg"
},
];
console.log(stories[1].caption); // "better"
Now once you find the clicked object, you can just ask it what it's caption is. And you can pass the whole object to the popup maker. And no field is handled differently or passed around in a different manner, because you are not passing around the fields. You are passsing the entire object.

change background img each time by clicking link

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...
Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Categories

Resources