I have working codes that sets the Prev and Next URL based on the available pages numbers and the URL you are currently on.
My codes are way too long and not flexible at all. How can I make it more flexible and production ready?
http://jsfiddle.net/sunflowersh/ppDL7/5/
var currentindex = '4'; //updated based on the current index data
var indexNum = parseInt(currentindex);
var currentURL = document.location.href.substring(document.location.href.lastIndexOf("/")+1, document.location.href.length);
var baseURL ="/en_US/";
var leftURL = "";
var rightURL = "";
switch(indexNum)
{
case 2:
// if there are only index, index1, and index2
if((currentURL.indexOf("index.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 3:
// if on index3.html or index.html
// make the right arrow URL go back to index1.html
if((currentURL.indexOf("index3.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-2) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 4:
if((currentURL.indexOf("index4.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-3) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 5:
if((currentURL.indexOf("index5.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-3) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
default:
// if no current index, disable the link
leftURL= baseURL + "#";
rightURL= baseURL + "#";
}
var leftArrow =$(".leftArrow").find("a").attr("href",leftURL);
var rightArrow =$(".rightArrow").find("a").attr("href",rightURL);
Have a see at this http://jsfiddle.net/steelywing/ppDL7/6/
Create a index.js
var baseURL = "/en_US/index";
var maxIndex = 4;
function updateNav(index) {
if (index-1 > 0) {
$('.leftArrow a').attr('href', baseURL + (index-1) + '.html');
} else {
$('.leftArrow a').hide();
}
if (index+1 <= maxIndex) {
$('.rightArrow a').attr('href', baseURL + (index+1) + '.html');
} else {
$('.rightArrow a').hide();
}
}
and, in every index.html, call updateNav() onLoad
<script>updateNav(2); // 2 current index </script>
If you need to parse the URL, try using RegExp /\/index(\d+)\.html$/ (http://jsfiddle.net/steelywing/uex5m/)
MVC design would suggest rendering Next & Prev URLS on the server, which knows how many pages there are in total;
Or at least rendering a pre-prepared 'base URL' and 'pageCount' into JS variables, so producing a valid URL is trivial in Javascript.
An example in JSP:
<script type='text/javascript'>
var baseUrl = ${baseUrl};
var numPages = ${numPages};
var currPage = ${currPage};
function changePage (delta) {
var newPage = ((currPage + delta) % numPages); // 0-based.
var newUrl = baseUrl + newPage + ".html";
// var newUrl = baseUrl + newPage;
window.location = newUrl;
}
$(document).load( function(){
$(".leftArrow a").click( function(){
changePage(-1)});
$(".rightArrow a").click( function(){
changePage(+1)});
});
If your page-numbers are 1-based, the % 'modulus' expression either has to be more complex (subtract 1 beforehand, add 1 after) or you can do an if statement.
function changePage (delta) { // 1-based PageNumber version.
var newPage = currPage + delta;
if (newPage <= 0) newPage = numPages;
if (newPage > numPages) newPage = 1;
// ... as before.
Or via modulo:
var newPage = ((currPage-1 + delta) % numPages) + 1;
Pick which you find clearest & most maintainable, if you were coming back to the code in 2 years time!
[Edited] If no server-side smarts at all, just put constants into the JS. You can also separate the constants/or calculation of base-URL, from the active part of the script.. thus making it reusable across several pages.
If i understand your use case correctly, this should do what you want:
$(function () {
var total = 3; // index.html, index1.html, index2.html
var currentIndex = 0; // index.html
var base = '/en_US/';
var pagename = 'image'; // for pattern: index<number>.html
function getNavUrl(delta) {
var newIndex = (currentIndex + delta < 0) ? total - 1 : (currentIndex + delta) % total;
newIndex = (newIndex === 0) ? '' : newIndex;
return base + pagename + newIndex + '.html';
}
$(".leftArrow a").click(function () {
window.location = getNavUrl(-1); // /en_US/index2.html
});
$(".rightArrow a").click(function () {
window.location = getNavUrl(+1); // /en_US/index1.html
});
});
version with more detailed comments: http://jsfiddle.net/ppDL7/8/
Update:
After figuring out the exact recuirements, here is the final version. Also added index parsing from document.location.href:
$(function () {
var total = 4;
var base = '/en_US/';
var pagename = 'index'; // for pattern: index<number>.html
var currentIndex; // index.html === index[last].html
var href = document.location.href;
function extractIndex(url){
var regExp = new RegExp(pagename+'(\\d+)\.html$');
var match = url.match(regExp);
var index = match? match[1] : null; // null if url does not match
// interpret index.html as index[last].html:
return (!index)? total : +index;
}
function getNavUrl(delta) {
var newIndex;
if(currentIndex +delta <= total){
newIndex = (currentIndex + delta <= 0) ? total : (currentIndex + delta) % (total+1);
} else {
newIndex = (delta < 0)? total - delta : delta;
}
return base + pagename + newIndex + '.html';
}
function setCurrent(index){
$('.current').html('<b> ' + index + '</b>');
}
currentIndex = extractIndex(href);
$(".leftArrow a").click(function () {
window.location = getNavUrl(-1);
});
$(".rightArrow a").click(function () {
window.location = getNavUrl(+1);
});
});
http://jsfiddle.net/ppDL7/12/
Related
I am having a language selection radio button in my html page and on selection of a language I make the call to the same url appending '?lang='. This I am doing via js and when the url is submitted the & is replaced with ?. Below is my js code.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
$(document).ready(function () {
$('input:radio[name=lang]').change(function() {
var url = window.location.href;
var selectedLang = $(this).attr('id');
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + selectedLang);
window.location = url;
} else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + selectedLang);
window.location = url;
}
} else {
if (url.indexOf('?') >= 0) {
window.location = url + '&lang=' + selectedLang;
} else {
window.location = url + '?lang=' + selectedLang;
}
}
});
});
Now when I make the language selection the url in the browser is http://localhost:8080/test/report.htm?count=40&name=jerry?lang=en. I debugged the code and saw url to be http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en but this is getting changed on submission.
Your code seems to be fine. You should consider to use functions, they make debugging a lot easier.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
function getLangUrl(url, lang){
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + lang);
return url;
}
else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + lang);
return url;
}
} else {
if (url.indexOf('?') >= 0) {
return url + '&lang=' + lang;
} else {
return url + '?lang=' + lang;
}
}
}
var url;
url = "http://localhost:8080/test/report.htm";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
I've coding pagination with JS
out like this
<a id="prev">Previous Page</a>
<a id="next">Next Pages</a>
and JS Code like this
$('#next').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = parseInt((url.substr(urllen-1)).substr(0,1));
var nurl = url.substr(0,(urllen-1))+(cur+1);
if(cur=="NaN") { window.location = (url); }
else { window.location = (nurl); }
});
$('#prev').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = (url.substr(urllen-1)).substr(0,1);
if(cur==1||cur=="NaN") { window.location = (url); }
else { var nurl = url.substr(0,(urllen-1))+(cur-1); window.location = (nurl); }
});
and my url like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=1
let's me explain the reason that i'm using a JavaScript method is i don't want to change my URL that containing page variable that i use in my whole page
so what i'm doing is get all the URL and change bike_id value to next/prev
and the problem is when it count to 19 or URL like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
then i goes next again the URL will become
http://localtest/rftpages/record.html?s=1&l=1&bike_id=110
any idea/suggestion to fix this ?
Thanks
What you should do is grab the page from the query string and the either increment or decrements it based on what is clicked.
all you need is this function to get the parameters:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
So if I assume your example:
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
Then you can change your function to be:
$('#next').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage + 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});
$('#prev').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage - 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});
I wrote a javascript function that you can use to add parameters to your current URL. It returns your current URL with added parameters. I am not sure if this function will work on all browsers. Currently it works in my Chrome browser perfectly. Can you please tell me disadvantages of this function or how can I improve it or any other way to do the same thing?
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.indexOf("?");
if (flag == -1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + param_key + "=" + param_value;
}
return newURL;
}
I would send the path as a parameter to the function, because you won't always be just using the current window.href, you might want to send some other path as well.
You can then remove some redundancy by dealing with the param separator before adding to the path.
And this will work in a loop when you have more than one parameter to add.
function AddParamToURL(currentPath, param_key, param_value)
{
var flag = currentPath.split("?");
var paramSeparator = (flag.length <= 1) ? "?" : "&";
return currentPath + paramSeparator + param_key + "=" + param_value;
}
Fixed the case where there could be a ? without any key after it and added & in second case
Fiddle : http://jsfiddle.net/0spsjeaL/3/
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.split("?");
if(flag.length <= 1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + "&" + param_key + "=" + param_value;
}
return newURL;
}
alert(AddParamToURL('name', 'John'));
You can inline a lot of stuff and param_key + "=" + param_value is duplicate code. Also you are forgetting & between parameters.
function AddParamToURL(param_key, param_value)
{
var url = window.location.href;
var newUrl = url.indexOf('?') < 0 ? url + '?' : url + '&';
return newUrl + param_key + '=' param_value;
}
I know that this question has been asked multiple times, but my case is different. So I have an external JavaScript file which contains the code for my accordion menus (you know, the user clicks on a title and it expands). Now I want to get a # (hash sign) from the url and according to it to open a specific "accordion" onload.
So here's what I've tried:
<body onload="runAccordion(index);"> <!-- In the example bellow, index should be equal to 1 -->
But it never worked (as desired), because I don't know how to "read" the url's # (element's id)...
Here's the markup for an accordion:
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1);">
<div class="AccordionTitle" id="AccordionTitle1">
<p>Title</p>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<p>
<!-- Content -->
</p>
</div>
Or maybe I should use PHP $_GET???
JS file contents:
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
Give the following a try:
$(document).ready(function() {
var hash = window.location.hash;
hash = hash.length > 0 ? hash.substring(1);
if (hash.length) {
runAccordion(window.location.hash);
}
});
The above will grab your hash index out of the URL. To add a hash to the URL, try the following:
window.location.hash = 1; //or whatever your index is
# You can use: #
window.onload = function() {
runAccordion(window.location.hash);
}
i have a JavaScript code of photo gallery with a slider but there's a problem :
var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";
// check if the file is exiset -- it's running in bar() function -- run on servers and local host.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
return http.status != 404;
}
// push images paths to array
function bar() {
var exict = 0;
var counter = 0; //counter of array's index
for (var i = 1 ; exict < 30; i++) {
// if there isn't .jpg or .gif
if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
exict = exict + 1;
}
// if there is .jpg
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
counter = counter + 1;
}
// if there is .gif
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
gifIndex.push(i);
counter = counter + 1;
}
}
}
but it was not work, so i tried to change var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;
but I got error: "error CS1012: Too many characters in character literal". I'm still not sure that this is the issue, as my original code does work (you can see the initial product image loaded when you visit the site .baumhaus and click on a product range and then any product, you will see the action - before it disappears once it tries to render the thumbnails).
How about
var partnum = '<%= Request.QueryString["partno"] %>'";