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
Related
I have a button in index.html. after click on this button, I want to append an image in body section of page2. The following code only opens page2 but the rest of code doesn't work. What I am doing wrong? thanks
function ready()
{
var w = window.open("Page2.html");
w.onload = function(){
var p = document.createElement("img");
x.setAttribute("src", "ts_WWW_2016w03.jpg");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
w.document.body.appendChild(p);
};
}
Method 1:
One way to do this is by making use of query string, it could be like this:
Plunker Demo 1
page1.html
<h1>Page 1</h1>
<button id="clickMe">Open New Page</button>
<script>
document.getElementById("clickMe").addEventListener('click', ready);
function ready() {
var $s = 'http://lorempixel.com/400/200/city/2/',
$w = '400px',
$h = '200px',
//we combine the three into one string using '&' as a delimiter
$qs = $s + '&' + $w + '&' + $h;
//then we add that final string as query to the href
window.open('page2.html?' + $qs);
}
</script>
page2.html
<h1>Page 2</h1>
<script>
// we first grab page href, extract that string we injected in
// page1 which comes after the '?' mark.
// then we split the string into an array with three elements.
var a = location.href,
b = a.substring(a.indexOf("?") + 1),
qStrings = b.split('&'),
$img = document.createElement("img");
// because of how we combined the string in page 1, the first
// element of the array represents the 'src'
// the secodn elements represents the 'width' and the last
// on is the 'hight'.
console.log(qStrings);
$img.setAttribute("src", qStrings[0]);
$img.setAttribute("width", qStrings[1]);
$img.setAttribute("height", qStrings[2]);
//then we append the image
document.body.appendChild($img);
</script>
Method 2:
You can also achieve it using sessionStorage or localStorage,
IMHO this is better because the url in the address bar of page2 tab won't look like a mess and could be a better way to avoid errors comparing to method 1.
Plunker Demo 2
page1.html
<h1>Page 1</h1>
<button id="clickMe">Open New Page</button>
<script>
document.getElementById("clickMe").addEventListener('click', ready);
// we create three session keys for src, width and height
// and we set their values, then we launch page2
function ready() {
sessionStorage.setItem('$src', 'http://lorempixel.com/400/200/city/2/');
sessionStorage.setItem('$width', '400px');
sessionStorage.setItem('$height', '200px');
window.open('page2.html');
}
</script>
page2.html
<h1>Page 3</h1> back to page 1
<script>
// First, just in case a user opens page2 before clicking the button in page1,
// we check if the session item we need have been set or not, if yes we proceed
if (sessionStorage.getItem('$src') && sessionStorage.getItem('$width') && sessionStorage.getItem('$height')) {
var $img = document.createElement("img");
// we get the session values and set them as values of
// the image attributes, then we append the image
$img.setAttribute("src", sessionStorage.getItem('$src'));
$img.setAttribute("width", sessionStorage.getItem('$width'));
$img.setAttribute("height", sessionStorage.getItem('$height'));
document.body.appendChild($img);
// this is optional but it might be a good practice to
// remove the session items
sessionStorage.removeItem('$src');
sessionStorage.removeItem('$width');
sessionStorage.removeItem('$height');
}
</script>
I have through test on last version of chrome.
the x is not define: x.setAttribute.
function ready()
{
var w = window.open("Page2.html");
w.onload = function(){
var p = document.createElement("img");
p.setAttribute("src", "images/ts_WWW_2016w03.jpg");
p.setAttribute("width", "304");
p.setAttribute("height", "228");
w.document.body.appendChild(p);
};
}
ready();
I'm trying to make a link, when user clicks it to change URL randomly to one of the vars.
$(".link").click(function(){
var safeLangs = ['en','al','de','fr','gr'];
var rand = function() {
return Math.floor(Math.random()*6);
};
var randomLangFunction = function() {
var randomLang = safeLangs[rand()];
return randomLang;
};
url = "?lang=" + randomLang();
window.location = url;
})
Problem is fixed by, thanks.
By Scott Marcus
At the end of your code, you incorrectly call your function: randomLang(); when it is really: randomLangFunction(). I also removed your rand function and incorporated it into the other.
$(".link").click(function(){
var safeLangs = ['en','al','de','fr','gr'];
var randomLangFunction = function() {
// No need to make a separate function for the random since
// this function is part of that process. Also, don't hard
// code "6" as the random multiplier as that will need to
// change if you add more languages. Just get the length
// of the languages array:
return safeLangs[Math.floor(Math.random()*safeLangs.length)];
};
url = "?lang=" + randomLangFunction();
console.log(url);
// Commented only for example to work:
// window.location = url;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" href="#">Click Me</a>
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.
Basically I want to create next and previous buttons for a JQuery Image Gallery I'm working on. Each button has an id of "next" and "prev" respectively. What I'm trying to do is change a number that is in the source of the main image in the gallery (which has an id of mainImg). I have been able to target the number within the source of each image but I can't seem to increment it correctly and then replace the current image's source number with the new, incremented number. I tried using a while loop, for loop, and if statement but none of them worked correctly. To see the gallery that I have so far, I have it uploaded here: http://tiger.towson.edu/~abarso2/463/projecta/index.html If you go into my script.js file you'll see a block commented out at the bottom. That is the function I have so far that targets the number within the image's source and parses it to an integer. Thanks in advance for any help.
Here's what I have currently:
(function(){
var mainImg = $('#mainImg').attr('src');
var mainImgStr = mainImg.charAt(mainImg.length - 5);
var mainImgNum = parseInt(mainImgStr);
$('#next').click(function(){
});
}());
This should solve your problem
$(function(){
var mainImg = $('#mainImg');
var slidshow = $('#slideShow');
$('#next').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var next = $('img[src="' + src +'"]', slidshow).next();
if(next.length){
mainImg.attr('src',next.attr('src').replace('thumb','shot'));
}
});
$('#prev').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var prev = $('img[src="' + src +'"]', slidshow).prev();
if(prev.length){
mainImg.attr('src',prev.attr('src').replace('thumb','shot'));
}
});
});
Here is the revised code. The regexp will work better. The user can click the next button multiple times but no image will be skipped as the main image will only go to the next if and when the next image is loaded. So if you click next quickly 5 times only the next image will show (not skipping 4 images).
(function(){
// replace all non digit characters from src
// only the last set of numbers so www.123.com/image7.jpg
// will give us 7
function getNumber(src){
return parseInt(src.replace(/[\d]+(?=[\/])/g,"")
.replace(/[^\d]/g,""),10);
}
// replaces last number of a source with the number provided
// www.123.com/imgage7.jpg will be www.123.com/image8.jpg
// if number 8 is given
function setNumber(src,num){
return src.replace(/[\d]+(?![\d])/g,num);
}
var $mainImg = $('#mainImg');
$('#next').click(function(){
var src= $mainImg.attr('src'),
mainImgNum = getNumber(src);
var $img=$(document.createElement("img"));
$img.data("checkNext",false);
$img.on("load",function(){
// image exsist, load it as main image src
if($img.data("checkNext")===true){
$img.remove();
}else{
$mainImg.attr('src',$img.attr('src'));
$("#prev").show(1000);
$img.data("checkNext",true);
$img.attr('src',setNumber($img.attr('src'),
new String(mainImgNum+2));
});
$img.on("error",function(){
if($img.data("checkNext")===true){
$("#next").hide(1000);
}
// clean up
$img.remove();
});
$img.attr('src',setNumber(src,new String(mainImgNum+1)));
});
}());
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