I would like to change the url of the page when the user select another page to visit. The url is dynamically replace the original one.
eg.
If user visit page 1 , the url will be book.html?page=1
If page 30 then book.html?page=30 and so on.
However, when I change the link using javascript, it falls into a infinite loop.
It seems I keep visit->change link ->visit ->change link->.... How to fix this problem?
eg. When the link change, don't access the page.
var currURL = $(location).attr('href');
var index = currURL.indexOf('?');
currURL = currURL.substring(0, index != -1 ? index : currURL.length);
// fall into loop
$(location).attr('href', currURL + '?page=' + pageNo);
You can do this pretty easily with just standard javascript.
if(location.href.indexOf('?') !== -1 && location.href.indexof('?page=') === -1)
{
var urlArray = location.href.split('?');
var newURL = urlArray[0] + "?page=" + urlArray[1];
location.href = newURL;
}
Related
I'm trying to make a JSP that refresh itself every 2scd approximately and keep what the user tip in input form.
My idea was to save the input with javascript, add them to the URL and refresh the page, then retrieve and set the input.
This is my JS code :
$(document).ready(function () {
function refreshPage(){
var mapValue = new Array();
var mapName = new Array();
var i = 0;
$(".positionInput").each(function() {
mapValue[i] = $(this).val();
mapName[i] = $(this).attr("name");
i++;
});
var parameters = "";
for(i = 0; i < mapName.length; i++){
if(mapValue[i] != ""){
parameters += "?" + mapName[i] + "=" + mapValue[i];
}
}
window.location.href = "http://localhost:8080/drawinguess/waitingplayer.jsp" + parameters;
setTimeout(refreshPage, 2000); //execute itself every 2s
}
refreshPage();
});
But the timer get crazy (even with 1mn delay), it refresh itself as fast as he can with window.location.href (without this, it's working fine)
Thanks in advance if you have any other idea or if I'm making something wrong
You could try and use local storage for this. The best way would be that instead of refreshing the entire page, you only refresh what is needed by having services set up and using an async function like fetch() to hit those services and update the page.
I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
This should get you started (starting with your original code).
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
Of course, this would be easier:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
And this would be easiest (using the file name):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
You can do this with PHP or JS. But in either case you first need to be able to programmatically determine the page number of the currently displayed page.
You mention PHP, is this WordPress or some other similar CMS?
Okay so you mentioned that this is a basic website, but we still need to be able to pull that currentPageID. We could do this a few ways, the coolest would probably be to take it from the url, so let's do that.
To get the number from the url structure you mention in comments (hostname.com/page-1.html):
// Let's first grab the url and pull just the last segment, in case there are numbers anywhere else in the url.
var url = window.location.href;
var array = url.split('/');
var lastSegmentOfUrl = array[array.length-1];
// Next, let's regex that last segment for the first number or group of numbers
var reg = /\d+/;
var currentPageID = lastSegmentOfUrl.match(r); // That's it!
// Then some basic math to get the next and previous page numbers
var previousPageID = currentPageID - 1;
var nextPageID = currentPageID + 1;
// And finally we change the href values on the next and previous <a> elements
document.getElementById('previous').href('/page-' + previousPageID + '.html');
document.getElementById('next').href('/page-' + nextPageID + '.html');
This will keep working forever assuming your url structure stays the same insofar as the last segment only has the current page number and no other numbers, and also that the next and previous anchor tags ID's don't change.
Here is a method using location.pathname and String.prototype.replace, no extra templating required!
Update Includes check that page exists before fetching.
// Check that a resource exists at url; if so, execute callback
function checkResource(url, callback){
var check = new XMLHttpRequest();
check.addEventListener("load", function(e){
if (check.status===200) callback();
});
check.open("HEAD",url);
check.send();
}
// Get next or previous path
function makePath(sign){
// location.pathname gets/sets the browser's current page
return location.pathname.replace(
// Regular expression to extract page number
/(\/page\-)(\d+)/,
function(match, base, num) {
// Function to increment/decrement the page number
return base + (parseInt(num)+sign);
}
);
}
function navigate(path){ location.pathname = path; }
var nextPath = makePath(1), prevPath = makePath(-1);
checkResource(nextPath, function(){
// If resource exists at nextPath, add the click listener
document.getElementById('next')
.addEventListener('click', navigate.bind(null, nextPath));
});
checkResource(prevPath, function(){
// If resource exists at prevPath, add the click listener
document.getElementById('prev')
.addEventListener('click', navigate.bind(null, prevPath));
});
Note that this will increment the "page-n" portion of the path, even if you are in a sub-path. It will also work for non-html extensions.
E.g.,:
mysite.com/page-100/resource => mysite.com/page-101/resource
or
mysite.com/page-100.php => mysite.com/page-101.php
I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.
I change current url of the webpage using window.history.replaceState() without refreshing the page. so that I can append to current url YouTube VideoID when ever user clicks on the video which are listed on this page and plays the same video in the same page.
Let us assume sample urls are -
Default Video page
http://www.domain.com/video/
After User clicks on video URL changes to removing the last /
http://www.domain.com/video#Se1y2R5QRKU
I want url to remain with /
http://www.domain.com/video/#wckLzQDTm6s
Here is the script I am using but I am not sure what is remove last / from the url
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = URL.match(regExp);
if (match && match[7].length == 11) {
//console.log(match[7]);
currentURL = document.URL;
// alert(currentURL.slice(0, currentURL.lastIndexOf('#')));
console.log(currentURL.slice(0, currentURL.indexOf('#')));
var sliceURL = currentURL.slice(0, currentURL.indexOf('#'));
var newURL = sliceURL + '#' + match[7];
window.history.replaceState(null, "Video Gallery", newURL);
return match[7];
} else {
//alert("Could not extract video ID.");
}
Because your currentURL initially does not contain the #, the indexOf will return -1 and the result is that the last character (your slash) will be removed. You should explicitly check whether the hash is inside the currentURL before slicing it:
var hashIndex = currentURL.indexOf('#');
var sliceURL = (hashIndex != -1) ? currentURL.slice(0, hashIndex) : currentURL;
How can I convert this:
http://example.com/?thisurl
to this:
http://example.com/#/thisurl
I have a bunch of old URLs that need to redirect to specific anchors on my page but I can't do it with htaccess because the anchors don't get passed through.
Any thoughts?
Something like this should work:
window.location.href = window.location.href.split('?')[0] + '#/' +
window.location.search.replace(/^?/, '');
You can use the .hash and .search parts of the window.location object like this:
window.location.hash = "/" + window.location.search.substr(1);
This will set the hash without reloading the page.
If you want to reload the page so it has a new URL (without the ?thisUrl in the URL bar, then you could do this:
var wl = window.location;
if (wl.search.length > 1) {
wl.href = wl.href.replace(/\?.*$/, "") + "#" + wl.search.substr(1);
}