I got a script that opens links randomly ... but I needed to know how I create a script to open a link by myself and then return to the initial one. Eg... Click on the button and it opens link1. Click it again and it opens link2 ... again and opens link3 .... then opens link4 .... and then opens link1 again.
I'm using this script to make him open the link randomly .... but I need it to be sequential and after opening the last link he opens link1 again. Can you help me guys?!
Best regards!
Alex.
<script>
<! -
/ *
Random Links Button
* /
// Specify the links to work at random below. You can enter as many as needed
var randomlinks=new Array()
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
function randomlink(){
window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)]
}
// - END OF SCRIPT-
</script>
You should be able to modify a global variable, which acts as a click counter, from within the function. eg:
var randomlinks=new Array();
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
var i=0;
function clickroundrobin(e){
if( i >= randomlinks.length )i=0;
var url=randomlinks[i];
i++;
window.location=url;
}
To test:
var randomlinks=new Array();
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
var i=0;
function clickroundrobin(e){
if( i >= randomlinks.length )i=0;
var url=randomlinks[i];
i++;
//window.location=url;
alert( url )
}
<a href='#' onclick='clickroundrobin(event)'>Click</a>
You can do this using window.open and by iterating the variable value on the button and pass the it as array index
<button onclick="randomlink()" >Random Link</button>
<script>
Links = []
Links.push("https://alloytech.wordpress.com");
Links.push("https://www.google.com/");
Links.push("https://www.youtube.com/");
Links.push("https://www.stackoverflow.com/");
var randomParam=0;
function randomlink() {
randomParam = randomParam >= Links.length?0:randomParam;
window.open(Links[randomParam],'popUpWindow','height=400,width=800,scrollbars=yes');
randomParam++;
}
</script>
I think this is what you are expecting
Related
I am using the following javascript (provided by m59 in this previous answer) to hide the destination of a link which usually shows up at the bottom of the browser window when hovering over a link:
<div>
<a data-href="http://www.google.com/"> LINK </a>
<script type="text/javascript">
var anchors = document.querySelectorAll('a[data-href]');
for (var i=0; i<anchors.length; ++i) {
var anchor = anchors[i];
var href = anchor.getAttribute('data-href');
anchor.addEventListener('click', function() {
window.location = href;
});
}
</script>
</div>
This works perfectly fine, but I would like the link to open in a new tab as well. How do I have to change the script in order to do so?
I tried using window.open('href','_blank'); instead of window.location = href; which did not work.
Unless im missing something, the most obvious thing to do is add a target to that anchor:
<a data-href="http://www.google.com/" target="blank"> LINK </a>
This is how to do it (try it on your code, stackoverflow blocks new tabs and links)
var anchors = document.querySelectorAll('a[data-href]');
for (var i=0; i<anchors.length; ++i) {
var anchor = anchors[i];
var href = anchor.getAttribute('data-href');
anchor.addEventListener('click', function() {
window.open(href,'','');
});
}
<div>
<a data-href="http://www.google.com/"> LINK </a>
</div>
You can see here, that syntax of window.open is:
var window = window.open(url, windowName, [windowFeatures]);
So to open link in new tab you should use something like:
var myNewTab = window.open(url, '_blank');
It will not work if you window is opened as '_blank'
Did you try window.open(href)?
i.e. In your example, href is a string (there are single quotes around it) as opposed to a variable.
Why not just use an onclick event handler to redirect the user?
link
function onClick(e) {
e.preventDefault();
document.location.href='www.google.ca';
}
I'm trying to open build a system which opens a new link every time an anchor tag is clicked. I tried using random function but at times it opens the same link again and again. But whereas as I want the link to open in an order and follow the cycle.. That is if I have three links, the user clicking the anchor text first time will open the first link, then second, then third and later again the first link..
This means the link must change if a different user clicks.
Here is a code that I found which uses random function..
<script type="text/javascript'>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.codingforums.com"
var link2="http://www.cssdrive.com"
var link3="http://www.dynamicdrive.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
so can someone help me out with this?
I tried using random function but at times it opens the same link again and again
You're probably getting the same link several times in succession due to the random calculation that you're using.
Try the following instead:
var myrandom=Math.floor(Math.random()*3);
You should get a better distribution this way.
Now, regarding your original question, if you want a persistent state to be kept between page reloads, so that each time the link is different, you'll probably need to use cookies or localStorage for storing what was the last used index for that user.
Example:
var links = ['http://www.codingforums.com', 'http://www.cssdrive.com', 'http://www.dynamicdrive.com'];
function nextLink() {
var index = localStorage.getItem('lastPos') || -1;
index = (index + 1) % links.length;
localStorage.setItem('lastPos', index);
return links[index];
}
What you need to do is save the index of the link, and then increase it every time so that you cycle through the links in order.
Here's a working example of what you want:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var urlIndex = 0;
function openUrl(){
url = urls[urlIndex % urls.length];
window.location = url;
urlIndex ++;
}
</script>
Get a link
</body>
</html>
Here's a demo :)
First of all, you have to list your links in an array. Second, you have to define a variable that hold the last opened link's index in that array, to void a successive opening of the same link (indeed it's a URL). In general you may follow something like the following code:
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
var lastUrl = '';
function getRandomIndex(arr){
return Math.floor(Math.random() * ((arr.length+1) - 1));
}
function openUrl(){
url = urls[getRandomIndex(urls)];
do {
if (url == lastUrl){
url = urls[getRandomIndex(urls)];
}
else{
lastUrl = url;
//Using alert instead of window.location for testing
alert(url)
//window.location = url;
}
}
while (lastUrl != url);
}
Then for test:
Click here for test
This is an online Demo
Reference: Generating random whole numbers in JavaScript in a specific range?
Edit
According your comment, the requirement is pretty easier, instead of choosing according to random value, you will define lastUrl as an integer store and every time the openUrl() is called, it will be increased by 1 after checking its value if it is greater than urls array length or not as follows:
Modified openUrl
urls = ['http://domain1.com','http://domain2.com', 'http://domain3.com', 'http://domain4.com'];
//lastUrl Index in urls array
// Global variable
var lastUrl = 0;
function openUrl(){
if (lastUrl > (urls.length - 1)){
//reset it to 0
lastUrl = 0;
}
else{
url = urls[lastUrl];
lastUrl++;
alert(url)
//window.location = url;
}
}
var myrandom = 0;
function random_3(){
myrandom += 1;
var link1="http://www.codingforums.com";
var link2="http://www.cssdrive.com";
var link3="http://www.dynamicdrive.com";
if (myrandom==1)
window.open('http://www.codingforums.com','_blank');
else if (myrandom==2)
window.open('http://www.cssdrive.com','_blank');
else if (myrandom==3)
window.open('http://www.dynamicdrive.com','_blank');
else if (myrandom>3)
window.open('http://www.codingforums.com','_blank');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
You can count click like user click on button and basis on this manage.
I have a help link. If a user clicks on it, it opens a new window with fixed width and height. It's working well except that when I right click the link, there is either no options to 'open in a new tab' (in IE) or I can open in a new tab but is directed to an empty page (chrome). Can any one help to make this like a link and also by default open in a new window (not a tab)?
<html>
<head>
<title>
link
</title>
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
</head>
<body>
<a id='PortOrderPageLearnMoreLink' href='javascript:' title='Learn more' onclick='activateHelpView("http://stackoverflow.com/")'>Learn more</a>
</body>
</html>
Use a real link, not the empty javascript: address. The onclick handler can prevent the link from doing anything "normal", but you'll have something for the right-click to work with.
target=_blank is a strong hint that you want the page opened in a new window, but whether that's honored at all -- and whether in a window or a tab -- is out of the page's control.
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
<a id='PortOrderPageLearnMoreLink' href='http://stackoverflow.com/' title='Learn more' onclick='activateHelpView(this.href); return false;' target='_blank'>Learn more</a>
A more modern way of handling all of this -- particularly if there will be more than one help link -- is to add a class to all of them, and run some JavaScript to add the click handler to each in turn. The HTML stays clean (and with real links, still works if JavaScript is disabled or not loaded).
var helplinks = document.querySelectorAll('.helplink');
for (var i = 0; i < helplinks.length; ++i) {
helplinks[i].addEventListener('click', activateHelpView);
}
function activateHelpView(event) {
event.stopPropagation(); // don't let the click run its course
event.preventDefault();
var helpUri = this.href; // "this" will be the link that was clicked
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
helpWindow.focus();
}
}
<a id='PortOrderPageLearnMoreLink'
href='http://stackoverflow.com/' title='Learn more'
class='helplink' target='_blank'>Learn more</a>
StackOverflow snippets aren't allowed to use some of these functions. A working example can be found here.
I'm writing a Greasemonkey script to automatically delete my notifications from a site, based on words I enter into a search box.
The delete "button" is basically a link, so I'm trying to open the first link in a new tab. Then, after it loads enough, open the rest of the links, one by one, in that same tab.
I figured out how to get the links I needed and how to loop and manipulate them. I was able to grab the first delete-link and open it in a new tab. I added an event listener to make sure the page was loaded before going to the next link.
I finally made that work so added my search box and button. Then I had to figure out how to wrap the whole thing in the event listener again.
So, I now have the whole thing working, except only the last link loads.
All links are going to my waitFor function so they should open, so it seems the event listener isn't working so it goes through the loop too fast and only the last link loads.
How do I make this script not continue the loop until the previous loaded page is fully loaded?
Complete code except for box and button creation:
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0]
var myrows = mytable.rows
//function openLinkInTab () {
//mywin2.close ();
//}
var mywin2;
mywin2 = window.open ("http://www.aywas.com/message/notices/test/", "my_win2");
var links;
var waitFor = function (i) {
links = myrows[i].cells[1].getElementsByTagName ("a");
mywin2 = window.open (links[0].href, "my_win2");
}
var delnotifs = function () {
var matching;
var toRemove;
toRemove = document.getElementById ('find').value;
alert (toRemove)
for (i = 0; i < 10; i++) {
matching = myrows[i].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
mywin2.addEventListener ('load', waitFor (i), false);
}
}
}
searchButton.addEventListener ('click', delnotifs, true);
So, why isn't it waiting for `mywin2.addEventListener('load', waitFor(i), false);`? I have a feeling it's something extremely simple that I'm missing here, but I just can't see it.
I also tried mywin2.addEventListener('load', function(){waitFor(i)}, false); and it still does the same thing, so it's not a problem of being a call instead of a pointer.
Swapping mywin2.addEventListener('load', waitFor(i), false); for
if (mywin2.document.readyState === "complete") { waitFor(i)} doesn't work either.
And while I'm at it... every time I see code looping through a list like this it uses
for(i=1;i < myrows.length;i++)
Which was skipping the first link in the list since arrays start at zero. So my question is, if I switch 'i' to zero, and the loop only goes while 'i' is < length, doesn't that mean it won't go through the whole list? Shouldn't it be
for(i=0;i != myrows.length;i++)
When you open a popup (or tab) with window.open, the load event only fires once -- even if you "open" a new URL with the same window handle.
To get the load listener to fire every time, you must close the window after each URL, and open a new one for the next URL.
Because popups are asynchronous and you want to load these links sequentially, don't use a for() loop for that. Use the popup load status to "chain" the links.
Here is the code to do that. It pushes the links onto an array, and then uses the load event to grab and open the next link. You can see the code in action at jsFiddle. :
var searchButton = document.getElementById ('gmPopUpBtn');
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0];
var myrows = mytable.rows;
var linksToOpen = [];
var mywin2 = null;
function delnotifs () {
var toRemove = document.getElementById ('find').value;
for (var J = 0, L = myrows.length; J < L; J++) {
var matching = myrows[J].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
var links = myrows[J].cells[1].getElementsByTagName ("a");
linksToOpen.push (links[0].href); //-- Add URL to list
}
}
openLinksInSequence ();
};
function openLinksInSequence () {
if (mywin2) {
mywin2.close ();
mywin2 = null;
}
if (linksToOpen.length) {
var link = linksToOpen.shift ();
mywin2 = window.open (link, "my_win2");
mywin2.addEventListener ('load', openLinksInSequence, false);
}
}
searchButton.addEventListener ('click', delnotifs, true);
See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener.
The second argument of the addEventLister function must be a pointer to a function and not a call.
I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?
function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });
Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load