How to Cycle Through Links (sequentially) Each Page Load - javascript

I'm trying to a cycle through 5 links and want to cycle through them on each page load (i.e. first visitor page load shows link 1, second visitor page load shows link 2, etc. then back to link 1 after link 5 shows)
I found this code below which does cycle through the links randomly, but I'm trying to get them to load in order. Is this possible? Thanks in advance for your help.
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var randomnumber=Math.floor(Math.random()*5)
document.getElementById("RotateLink").innerHTML = links[randomnumber];
</script>
(also, some tips on changing "link1" to an actual link would be helpful too)

Since you lose your JS context on page load, you could make use of the browser's inbuilt localStorage api (https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage).
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var numberFromStorage = localStorage.getItem("cycle-link-number") || "0"; // zero if getItem returns null
var number = parseInt(numberFromStorage); //cast to number since storage saves strings
number = number >= links.length ? 0 : number; // reset if reached max
localStorage.setItem("cycle-link-number", number + 1); //set item for next iteration
document.getElementById("RotateLink").innerHTML = links[number];
</script>
To create your link you could do something like this:
// instead of
// document.getElementById("RotateLink").innerHTML = links[number];
// do
var link = document.createElement("a"); // creates anchor element
link.href = 'someUrl'; // sets the url, e.g link.href = 'http://www.google.de';
link.innerHTML = 'linktext'; // set the link text
document.getElementById("RotateLink").appendChild(link); // appends the link to the element with the id "RotateLink"

As you need to know the link that was previously loaded after page reload, You need to store that information somewhere so that you can use it on the next reload. We have browser local storage to do that. You can store the index of the link that was previously loaded and increment the link based on that. More details about HTML5 Web Storage here here
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var currentIndex=localStorage.currentIndex;
if(currentIndex){
if(currentIndex < links.length-1)
currentIndex = parseInt(currentIndex)+1;
else
currentIndex = 0;
} else {
currentIndex = 0;
localStorage.setItem('currentIndex', currentIndex);
}
localStorage.currentIndex = currentIndex;
document.getElementById("RotateLink").innerHTML = links[currentIndex];
</script>

Related

How do I sequentially go down a list of links each time a user clicks a button?

I start with a button that activates the function onclick:
<button onclick="openStuff();">Click here!</button>
Then, I have an array of links like so:
var links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"];
Finally, I define the function that randomly applies a link to the button from the above array:
openStuff = function () {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'https://' + links[randIdx];
// open it in a new window / tab (depends on browser setting)
window.open(link);
};
The problem is I need it to not be random. Rather, I need it to go down the list sequentially as the user clicks the button. If the user clicks the button once it should go to the first link. But, if this user clicks the button a second time it should go to the second link in the list.
For example: User clicks button: Go to first link, User clicks button again: go to second link, and so on.
var linkIndex = 0;
openStuff = function () {
//when no more links are available to click then return
if(links.length <= linkIndex) return;
// construct the link to be opened
var link = 'https://' + links[linkIndex];
// open it in a new window / tab (depends on browser setting)
window.open(link);
linkIndex++;
};
You need a global index that start in 0. Then, inside the function you increment it after open the link.
var link = 'https://' + links[index];
index++;
I would do it like this:
var special_button_state = 0;
const links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"
];
const openStuff = function () {
var link = 'https://' + links[special_button_state];
if(special_button_state < links.length-1) {
special_button_state++;
}
window.open(link);
console.log(link);
};
<button onclick="openStuff();">Click here!</button>
You could have another variable set to the first index of the array, something like:
var linkTarget = 0
and then update linkTarget in the function to increment appropriately:
openStuff = function () {
// construct the link to be opened
var link = 'https://' + links[linkTarget];
// open it in a new window / tab (depends on browser setting)
window.open(link);
// update the index
if (linkTarget++ == links.length)
linkTarget = 0
};
You could also implement a dynamic label so that you know where it's going:
<body onload="setLink()">
<button id="turntable-button" onclick="openStuff()" />
</body>
Label setter on page load (put the same getElementById() line in openStuff() after updating the index):
setLink = function() {
document.getElementById("turntable-button").innerHTML = links[linkTarget];
}

Open pages with user lists and download the user ids

So I have a page which has a list of users, my total list of users is separated into 10 pages with each page showing 20 users. I want to open each page in a new window, pull the user ids on that window, close the window, and open the next page. Later I'll compile all this into a report. The problem I seem to be having is that the user_id_list only gets populated by the users on the first page so I have a bunch of duplicates.
Some of the code for parsing the pages.
full_page_string = document.getElementsByClassName("pagination")[0].outerText;
index_of_next = full_page_string.lastIndexOf("Next");
last_page_number = full_page_string.substring(index_of_next-3, index_of_next);
last_page_number.trim();
last_page_number = 2; /*DELETE LATER*/
page_array = [];
user_id_list = [];
/*Programatically create an array of pages*/
for (var page_num = 1; page_num <= last_page_number; page_num++) {
url = "example.com/users/"+ user_account_id + "/friends?page=" + page_num;
/*Open Each Page*/
var loaded_page = window.open(url, "page_" + page_num, "width=400, height=600");
page_array.push(loaded_page)
/*
For loop keps going even with settimeout. See if there is a way to delay a forloop. The thing is we need enough time to load a page, wait for it, grab users, close page, load a new page and repeat. Right now the floor loop makes it too fast.
Maybe Asyncronously open each page so they're their own instance or "thread"?
*/
loaded_page.onload = function () {
/*Find all users on the page by class*/
friends_on_page = document.getElementsByClassName("link span f5 fw7 secondary");
for (var i = 0; i <= friends_on_page.length; i++) {
pathname = friends_on_page[i].pathname;
user_id = pathname.substring(pathname.lastIndexOf("/")+1)
user_id_list.push(user_id)
console.log(user_id)
}
loaded_page.cose()
};
}

button to jump to next anchor

I have a wordpress-website with section scrolling enabled and added 2 buttons that should jump to the previous or the next page on the website and 2 buttons that should jump to the previous or next chapter on the website.
based on this post Goto Next Anchor Button I added the script but the browser returns the length = 0 for anchors, document.getElementByTagName() returns an array that is to big
and document.getElementByName() didn't work too.
var anchordivs = document.querySelectorAll('[data-anchor][data-id]');
var anchors = anchordivs.length;
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName = 0;
var anchorName = window.location.hash.replace(/#/,'');
if (anchorName){
for (var i=0, iLength=anchordivs.length; i<iLength; i++) {
if (anchordivs[i].dataset.anchor == anchorName) {
nextAnchorName = anchordivs[i+1 % iLength].dataset.anchor;
break;
}
}
}
if (!nextAnchorName){
nextAnchorName=anchordivs[0].dataset.anchor;
}
window.location.href = loc + '#' + nextAnchorName;
}
On button click the site should scroll to the next section of the website.
EDIT: wordpress did create the anchors as data-anchors in the respective divs:
<div ... data-anchor="c_home">. Here is what still does not work. On clicking the button the site does not jump to the new anchor and manually entering a anchor in the adressline of the browser does not work either. The JS-Code is tested and works now.
Maybe the problem for the missing jump is that it is all on one page?
I got it working by changing the last codeline to the following:
location.href ='#' + nextAnchorName;
location.reload();
Now its reloading the site with each click, but it works. That is not what i want.
I changed var anchors = document.body.getElementsByTagName("a"); and nextAnchorName = anchors[i++ % iLen].name;
function goToNextAnchor() {
var anchors = document.body.getElementsByTagName("a");
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName;
// Get name of the current anchor from the hash
// if there is one
var anchorName = window.location.hash.replace(/#/,'');
// If there is an anchor name...
if (anchorName) {
// Find current element in anchor list, then
// get next anchor name, or if at last anchor, set to first
for (var i=0, iLen=anchors.length; i<iLen; i++) {
if (anchors[i].name == anchorName) {
nextAnchorName = anchors[i++ % iLen].name;
break;
}
}
}
// If there was no anchorName or no match,
// set nextAnchorName to first anchor name
if (!nextAnchorName) {
nextAnchorName = anchors[0].name;
}
// Go to new URL
window.location.href = loc + '#' + nextAnchorName;
}

How to reset the value of one variable from one or more tab?

I have two tab. One is home tab and another one is home-1 tab. Here i tracking the time count for login to logout time. I have following code in one java script file. this work as two instance.
home tab -> www.example.com/home //(my java script file contain this directory) first instance.
home-1 tab -> www.example.com/home-1 //(required script file include from home tab into this tab) second instance.
Any key/mouse event will reset the counter.
var sestmout=0;
var idletm=60*1;
var idletmcntr=0;
var idletimeout=null;
var lastUpdate1 = new Object();
var lastUpdate = 0;
var curdttm = new Date();
$(document).ready(function(){
initidletm();
});
lastUpdate1.cntr = idletmcntr;
lastUpdate1.ctme = curdttm.getMilliseconds();
lastUpdate1.time = curdttm.getTime();
function reset_cnt(){
if(idletmcntr != 0){
curdttm = new Date();
lastUpdate1.cntr = idletmcntr;
lastUpdate1.ctme = curdttm.getMilliseconds();
lastUpdate1.time = curdttm.getTime();
var a = moment();
lastUpdate1.utme = a.valueOf();
}
idletmcntr=0;
}
document.onclick=function(){
reset_cnt();
};
document.onmousemove=function(){
reset_cnt();
};
document.onkeypress=function() {
reset_cnt();
};
In each tab I include above lines in java script file. Now I trigger the mouse/key event on home tab that reset counter value in home-1 tab.
Using this code.
function initidletm(){
if(window.name == "home-1"){
window.opener.document.onkeypress = document.onkeypress;
window.opener.document.onclick = document.onclick;
window.opener.document.onmousemove = document.onmousemove;
}else if(window.name == "home-2"){
window.opener.document.onkeypress = document.onkeypress;
window.opener.document.onclick = document.onclick;
window.opener.document.onmousemove = document.onmousemove;
}
else{ // home tab
document.onkeypress=function() {
reset_cnt();
};
document.onclick=function() {
reset_cnt();
};
document.onmousemove=function() {
reset_cnt();
};
}
}
clearTimeout(idletimeout);
idletimeout=setTimeout(trackidletm,1000);
function trackidletm() {
initidletm();
}
This approach is write or wrong. Only home tab reset the counter value to the home-1 and other tabs. The other tabs like home-1 tab does not reset the home tab and other tabs. What reason? And How to reset the other tab counter value from working tab?
Well you can write a functionality in such a way that, it would store a value in the HTML5 localStorage when you do something.
if (typeof(Storage) !== "undefined") {
localStorage.setItem("reset", "true");
}
And if you not doing anything it will set it to false.
localStorage.setItem("reset", "false");
You can check these values like this :
localStorage.getItem("reset");
So when you have different tabs of the same domain, you can check out and see if you did anything in another tab.
Ref : http://www.w3schools.com/html/html5_webstorage.asp
Hope it helps.

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

Categories

Resources