Change image when page refresh sometimes keep loading same image - javascript

im using this script to rotate and change image when the page is refresh it working ok but sometimes it keep loading the same image several times before change to the new image, is there a way to fix this?
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("headerbanner").src = theImages[x];
}
onload=changeImage

To achieve the image rotation behaviour that you require, you'll need to "remember" some state (ie the image that your were previously up to) between page loads. One easy way to do this is vial the LocalStorage API.
You can for instance, retrieve a previously stored value for a key via:
let lastIndex = localStorage.getItem('last_index');
And then use that to control which image is displayed from your array. You would also use:
localStorage.setItem('last_index', `${ lastIndex }`)
To update the stored value, for the next page reload. Together, these might integrate with your code like this:
/* Get the last stored index, and parse to an integer */
let lastIndex = Number.parseInt(localStorage.getItem('last_index'))
if(Number.isNaN(lastIndex)) {
/* If we got an invalid index (ie no previously stored value) set to default 0 */
lastIndex = 0;
}
else {
/* Otherwise increment the index counter. This is going to cause the image to
change every page load */
lastIndex ++;
}
/* Remember the updated index for future reloads */
localStorage.setItem('last_index', `${ lastIndex }`)
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
/* Use the modulo operators to get x based on lastIndex, and the total number
of images */
var x = lastIndex % size;
document.getElementById("headerbanner").src = theImages[x];
}
window.onload=changeImage
Remember to keep in mind that the LocalStorage API sets values as strings, which is why Number.parseInt(),etc is necessary.

A good way to achieve the rotation after refresh would be to save your previous image index in the url and change it each time.
1) you land on the page, the query parameter image is empty, you get image with index 1 and you set your url to mysite.com?imageid=1
2) you refresh, the query parameter is 1, you set it to 2 in the url and display the image (there is no randomness here but you never get the same image)
3) implement custom logic to fit any index, you can implement randomness !== to previous image id to always get a different image with a recursive while loop:
while (newImageId === queryParam.imageId) { getRandomImageId(queryParam.imageId)}
I am on my phone can't write the code but you can use window.location for the url

Save the current image into the local session.
localStorage.setItem('lastImage', imageIndex);
After page load...
localStorage.getItem('lastImage');
... and exclude it from your random mechanism or ever iterate.

Related

How do i link all this images with an array

How do i link all this images to an array, so as this links can work when i click each image slide
jQuery(document).ready(function() {
var bgImageArray = ["banner1.jpg", "banner2.jpg", "banner3.jpg"],
var links = ['http://google.com', 'http://hotmail.com', 'http://yahoo.com', 'http://kimjoyfox.com'],
base = window.location.origin + "/wp-content/themes/fbnquest/img/home/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
The way I understand your problem is the following :
For each time you click on one of each of the images, you want to redirect the user to one of the URLs, changing the URL each time the user click on the image.
Is it what you want ? If not, please can you precise your problem
[EDIT]
So yes,
Here is my way of solving your problem, If you don't matter, I won't give you code, obviously, you do this for training, let's do it :
Create an eventListener on click that will trigger a function called ChangeImageUrl (for example) and assign that eventListener to all the img elements
Then create a function that will detect the current URL of the image clicked, using imgElement.src ( i advice you to devide the src string using split or equivalent, that way you can directly access by index the current url )
Once you have the URL Use yourUrlArray.indexOf(currentImageSrcUrl), to catch the index of the current URL in your array, store it and increment it ( bonus if the increment value is upper than the URL array length, set it to 0 )
access the new src using yourUrlArray[newindex]
assign current img element the new src that we juste have extracted
Tell me if this answer is good for you, I hope it will
I was trying to understand what do you really want and I did something that I hope help you.
Inside of the loop you can do in this way below.
var i = new Image();
i.src = base + img;

Javascript - How to run part of the code only after the page refreshes?

Important: Even though this could probably be done with php (I'm using WooCommerce on Wordpress), I want this script to run only on my browser. That's why I want to do it in Javascript. Hence, I'm using Custom Javascript for Websites to load my script from my browser.
What my script should do: Check if the data of a specific element has been changed.
Logic: Step 1) Get and locally remember specific string (order number) of a specific class. Step 2) Refresh the page. Step 3) Again get the specific string (order number) of a specific class. Step 4) If strings do not match, run a function (play an audio).
Problem: After page reloads, the script starts to run again from the beginning. Hence, it results in overriding the stored string. As a result, stored and newly fetched string are always equal.
Question: How do I make the script to run the 3rd step only after refresh so that the stored data doesn't override itself?
Current code:
var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
localStorage.setItem("compareOld", compareOld); // Store this element in local storage, so that it can be used after page reloads.
setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.
var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new var.
var n = compareOld.valueOf(); // Turn stored element into a number (for easy comparison later).
var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Get the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
var m = compareNew.valueOf(); // Turn fetched element into a number (for easy comparison later).
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1Ao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AACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
} // Function that will play the sound.
if (n!=m) {
beep();
} // Run function if two numbers are not equal.
Additional: I have gathered the parts of the code from various Questions on stackoverflow. Meaning, I have been searching about this topic for the past week. This is my first questions ever. Hopefully I formatted the question so that it easy to understand.
EDIT: The issue has been solved. I used the idea of only running the first step of function on the first load of page. This post helped me to get functionality working https://stackoverflow.com/a/22334768/7929506
The working code looks like this:
function beep() {
window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}
if (sessionStorage.getItem("visit") == null) {
var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
sessionStorage.setItem("OrderIdOld", OrderIdOld);
sessionStorage.setItem("visit", new Date());
setTimeout("window.location.reload()", 10000);
}
else {
var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
var x = sessionStorage.getItem("OrderIdOld");
if (x==OrderIdNew) {
setTimeout("window.location.reload()", 10000);
}
else {
beep();
var x = sessionStorage.getItem("OrderIdOld");
sessionStorage.removeItem("OrderIdOld");
sessionStorage.removeItem("visit");
setTimeout("window.location.reload()", 10000);
}
}
When you refresh the page first time, you can simply append a flag variable to URL to identify weather its a refresh or a first time load. Based on that, you can pass a localized variable to script and if that is set then you need to refresh else not.

Redirect to random page (except the current page)

Solved! - didn't update my random number generation after changing from switch statement to array... ups. - Thanks!
Problem
Building a web comic and wanted to have one of those "random" buttons, where you jump to any of the strips. I'm assuming the best way to do this would be something on the back end (PHP or such), but I want to do it with JavaScript.
I got as far as picking a random page, but had the problem that it would sometimes redirect to the page it's already on (or rather often until I have more pages). I tried to make it take the page out of the array if the current page is the same as the target page, but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
I even made sure to use splice instead of delete. Doesn't that re-index the list?
Code
var pickRandomPage = function () {
// random Pages available
var links = [
"construction.html",
"placeholder.html",
"noplaymobil.html"];
// current Page
var currentURL = window.location.href;
var currentPage = currentURL.substr(currentURL.lastIndexOf('/')+1);
// get rid of current page from array of options
for(var i = 0; i < links.length; i++){
if(links[i] == currentPage){
links.splice(i,1);
}
}
// get a random number, rounded number between 0 and number of links
var randomPage = Math.floor((Math.random() * 3) + 1);
var link = 'http://bcitcomp.ca/students/hsloman/Comp1850/final/' + links[randomPage];
// open it
window.open(link,"_self");
};
Resources used sofar
Get current URL in web browser
window.open() should open the link in same tab
but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
The undefined is because your randomPage variable will contain a number between 1 and 3, but the actual valid indices in your links array are only either 0 or 1 because it will only have two elements after you remove the current page URL.
Change:
var randomPage = Math.floor((Math.random() * 3) + 1);
to:
var randomPage = Math.floor(Math.random() * links.length);
put this right before the window.open(...) line:
if(link === window.location+"") return pickRandomPage();
This is saying, "if the chosen link is the page we're already on, run the function again" ..so it will keep trying until a new page is given. This is easier than trying to splice the array.
See: recursion for more info.

Choose random image for every image Javascript

//Setting up the Array
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
// image source looks for the attribute, by using the variable arraying
$('img').attr('src',random);
Above is my code. I currently have javascript set up this way. The current code has the piece where images are randomly replaced from an image from the array. I want to have the code state that switch every image with a new random image, not every image with the same time. I like how it is random every time, but I also want to random for each picture.
Set up a loop to go over each image, pick a random one, and then assign to that one:
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
$("img").each(function() {
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
$(this).attr('src',random);
});
You can use a callback function with the attr method to calculate the value for each element:
$('img').attr('src', function(){
return arrayImg[Math.floor(Math.random()*arrayImg.length)];
});

How to use splice method to solve my problem correctly?

I am displaying rotating images.
var pics= [
"images/img1.jpg",
"images/img2.jpg",
"images/img3.jpg",
];
And would want it to stop onClick.
function StopRotate(interval, imgIndex) {
clearInterval(interval);
var permanentImage = picture[imgIndex].src;
picture[imgIndex].src = permanentImage;
pics.splice(pics.indexOf(picture[imgIndex].src), 1);
}
Here's how I rotate the images (this block has three occurrences for three image containers):
interval0 = setInterval(function () {
if(pics.length != 1) {
picture[0].src = pics[count];
count++;
if (count == pics.length) count = 0;
}
else picture[0].src = pics[0];
}, 10);
But the image occurs yet again to other frames even if the path has been already removed from the array. I tried this using 12 images. Some times when I run it, the src turns out to be undefined.
Also if I click the images unordered, the images from other frames becomes blank. In this sample, I have three images, if I clicked on the third container, the first container becomes blank, how does that affect other frames when the interval functions are separate. There's no problem however when clicking it in order. Note I have changed the sequence where I put the if condition inside setInterval.
The .src property will return a fully qualified pathname which will never be found in your array of partial path names when you try to look for it with .indexOf().
You can use .getAttribute("src") to get what is actually in the HTML and that should then match what you have in your array.
Example: http://jsfiddle.net/jfriend00/3H8XF/

Categories