switching between multiple URLs in HTML/javascript - javascript

Below is an example of what I would like but it has two flaws currently.
I believe that the order is incorrect because I cannot see any url sites beyond google.com. Something must be off in the location of certain items in the code. I have tried it without pop-up blockers and still cannot get the other windows to show.
I believe that this program is supposed to open in different windows/tabs. I would like mine to open the next url in the same window and tab and replace the original.
Google replaced by msn; msn replaced by yahoo
I am grateful for the help. Thank you everyone.
code:
<!DOCTYPE>
<html>
<body>
<script>
var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var wnd;
var curIndex = 0; // a var to hold the current index of the current url
function openWindow(){
wnd = window.open(urlList[curIndex], '', '');
setTimeout(function () {
wnd.close(); //close current window
curIndex++; //increment the index
if(curIndex < urlList.length) openWindow(); //open the next window if the array isn't at the end
}, 2000);
}
openWindow();
</script>
</body>
</html>

You can just reuse your window instance:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var wnd;
var curIndex = 0; // a var to hold the current index of the current url
function openWindow(){
wnd = wnd || window.open();
wnd.location.href = urlList[curIndex];
setTimeout(function () {
curIndex++; //increment the index
// If all urls have been showed, close our window instance
if(curIndex < urlList.length) openWindow(); else wnd.close();
}, 2000);
}
openWindow();
</script>
</html>

If you open in the same page your javascript will be gone. It won't work. As soon as google.com is opened that will be the end of your javascript. So you should open in either a new tab or consider using iframes.
See here for more info:
http://www.w3schools.com/tags/tag_iframe.asp

Related

javascript: open all links to pdf on a page in new window

I have a site that builds the pages dynamically. It's a SharePoint site. The site contains a lot of document libraries. The libraries contain word, excel and PDF documents. When a user clicks on a document, the document opens in the client application for office documents only. PDFs simply open in the same window. when people close the window containing the document, they close the site. I'm trying to use javascript to onload add target="_blank" to the PDF links.
So far I have:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
This code sort of works as some of the pdf links load in a new window as expected, some load in the parent window and some links load in both a new window and the parent. How do I tell the browser not to load in the parent window and only in the new window?
This is what I want to achieve:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
a.pdf<br /><br />
b.html<br /><br />
c.pdf<br /><br />
<script>
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
</script>
</body>
</html>
The problem I'm running into is that sharepoint document libraries are modifying the link behavior such that the javascript does not make then open in a new window. Below is an example of a link from a document library:
<a onfocus="OnLink(this)" href="https://rcd.sharepoint.com/HR/HR%20Policy%20Manual.pdf" onmousedown="return VerifyHref(this,event,'0','','')" onclick="return DispEx(this,event,'TRUE','FALSE','FALSE','','0','','','','','331','0','0','0x7fffffffffffffff','','')">HR Policy Manual</a>
If you don't have access to all elements for ahead with capturing all clicks on the page. Use addEventListener with enabled capturing for handling event. Test whether it's anchor tag and proceed to new page by own with code below:
document.addEventListener("click", function(e){
if (e.target.localName == 'a') {
var url = e.target.getAttribute('href');
e.stopPropagation();
// You can place extra checks here.
var tab = window.open(url, '_blank');
tab.focus();
}
}, true)
Do
Here is what I would do, I think I would collect the anchors and loop over them to check if the hrefs ends with .pdf and then add a function on all the .pdf links
Don't
Don't check for pdf files with .indexOf('.pdf'). Your check should fail If there's a filename called somedummyfile.pdf.something.png (which is a .png image) or any other formatted file.
Note that, new window might be blocked at user's end if they are using add-blockers.
Here is the Snippet:
function modifyLinks() {
let links = document.getElementsByTagName('a');
let properties = 'height=' + window.innerHeight + ',width=' + window.innerWidth + ',' + 'scrollbars=yes,status=yes';
for (i = 0; i < links.length; i++) {
if (links[i].href.endsWith('.pdf')) {
// links[i].setAttribute('target', '_blank'); // if you want to open them in new tab;
console.log(links[i].href);
links[i].addEventListener('click', function(e) {
e.preventDefault();
window.open(this.href, '_blank', properties);
})
}
}
}
window.addEventListener('load', modifyLinks);
File 1
File 2
File 3
HTML Link
Some Other file
I added the following JavaScript to get links containing "pdf" to open in a new window:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
I then noticed that document libraries were using a DispEx() javascript function on click of document links which negated the first bit of code. I had to overload the function with my own functionality.
function DispEx(a){
if (a.href.endsWith('.pdf')){
window.open(a);
return false;
}
}
Using both pieces of JavaScript in a content editor web part, I got PDF documents to open in a new window and all other links/documents to load in the same window.

How to open a new link everytime the page is reloaded by someone else?

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.

link on random image background

I have this code to have random background images, I need to make sure that when someone clicks on the picture to open a web page, one for each image. Can you help me please?
this is the code:
</head><body onLoad="LoadRandomBackground(); StartBackgroundRefreshTimer()">
</body>
</head>
<body onLoad="LoadRandomBackground()">
</body>
<script type="text/javascript">
var bgImages = [];
bgImages[1]="/img/sfondi/bg-stanem.jpg";
bgImages[2]="/img/sfondi/booking.jpg";
function LoadRandomBackground()
{
var randomImageIndex = Math.floor(Math.random()*bgImages.length)
document.body.background = bgImages[randomImageIndex];
}
function StartBackgroundRefreshTimer()
{
var timer = setInterval('LoadRandomBackground()',1000); // millisecondi
}
</script>
thank's
can someone help me?
you could create a second array ...
var bgImagesUrls=[];
then assign the urls to the array using the same indexes for the bgImages
you could then place in LoadRandomBackground
document.<someelement>.href=bgImagesUrls[randomImageIndex];
Here a short possible script http://jsfiddle.net/d2Dmh/3/
bgImages[0]= {url: ...
here you can place the url you want as destination as another parameter (destination : "url")
And with
window.location = "http://www.google.com/";
you can navigate to the new page in the document click function.
You need jquery for my example.

javascript slideshow links on the same page

I just copied JavaScript code from Google, and I don't know how to make a hyperlink that will be opened on the current page.
Here's the code which I inserted into the <head> section of my page.
var slideimages = new Array()
var slidelinks = new Array()
function slideshowimages() {
for (i = 0; i < slideshowimages.arguments.length; i++) {
slideimages[i] = new Image()
slideimages[i].src = slideshowimages.arguments[i]
}
}
function slideshowlinks() {
for (i = 0; i < slideshowlinks.arguments.length; i++)
slidelinks[i] = slideshowlinks.arguments[i]
}
function gotoshow() {
if (!window.winslide || winslide.closed) winslide = window.open(slidelinks[whichlink])
else winslide.location = slidelinks[whichlink]
winslide.focus()
}
Here's the code I inserted into the body section:
<script>
<!--
slideshowimages("main.PNG", "mainhover.PNG")
slideshowlinks('index.php', '_self')
//configure the speed of the slideshow, in miliseconds
var slideshowspeed = 2500
var whichlink = 0
var whichimage = 0
function slideit() {
if (!document.images) return
document.images.slide.src = slideimages[whichimage].src
whichlink = whichimage
if (whichimage < slideimages.length - 1) whichimage++
else whichimage = 0
setTimeout("slideit()", slideshowspeed)
}
slideit()
slideit()
//-->
</script>
Everytime I click on the image, the index.php page always appears on the new tab,
is there an easy way, so that the index.php page can be opened on the same page?
I know nothing about JavaScript.
Seeing the HTML will help understand the issue, but this code
if (!window.winslide || winslide.closed) winslide = window.open(slidelinks[whichlink])
else winslide.location = slidelinks[whichlink]
winslide.focus()
basically tells that if this is the first time you run it, then open a new window (window.open(slidelinks[whichlink]) which Chrome for example will use to open a new tab
Else if it's already created, change that window's location to the slide URL (else winslide.location = slidelinks[whichlink] e.g it's as designed to operate in a new window
to change it, you'll need to replace window.open with something that will operate on an iframe or something.
I'm not sure what is the purpose of opening a new window, but this is what the code does
On a side note, I'm not sure you found the best piece of code to run HTML based slides, If you want modern slides, I would try something like http://lab.hakim.se/reveal-js/

How to open a new window and insert html into it using jQuery?

I am trying to open a new window from javascript but nothing is being inserted into the html:
var callScriptText = $('#callScriptText').html();
var url = '/Action/CallScript/?callScript=';
// Open the current call script in a new window
var openWindow = window.open(url, 'callScriptPopup', 'width = 500, height = 500');
$(openWindow).html(callScriptText);
Does anyone know why?
Here's an example to open a new window with content using jQuery
<script>
function nWin() {
var w = window.open();
var html = $("#toNewWindow").html();
$(w.document.body).html(html);
}
$(function() {
$("a#print").click(nWin);
});​
</script>
<div id="toNewWindow">
<p>Your content here</p>
</div>
Open​
EDIT:
For those who say that this code doesn't work, here's a jsfiddle to try it http://jsfiddle.net/8dXvt/
Try this:
var x=window.open();
x.document.open();
x.document.write('content');
x.document.close();
I find it works in Chrome and IE.
Building upon #Emre's answer.
With javascript, you can chain, so I just modified the code to:
var x=window.open();
x.document.open().write('content');
x.close();
Also, to force it to a new window (not a new tab), give the first line dimensions. But it has to be the third argument. So change the first line to:
var x=window.open('','','width=600, height=600');
try:
var x = window.open('', '', 'location=no,toolbar=0');
x.document.body.innerHTML = 'content';
var codeContents = $("#contentsfornewWindow").html()
var win = window.open('', 'title', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1000,height=1000,left=200,top=70');
win.document.body.innerHTML = codeContents;
VS:
win.document.write(codeContents);
I have notice if there are iframes like youtubes videos , win.document.write loads the iframes where as document.body.innerHTML does not!

Categories