How to link to the current URL + 1 using JavaScript? - javascript

I'm looking to create a simple nav link that goes to the next or previous page in a series. The URL ends in a number and each successive page is just the next number in the sequence (.../101, /102, /103, etc). Is there a way to use javascript to link to the current URL + or - 1?
I know basically no javascript besides what I can copy and paste into HTML.
How do I solve this problem?

You need to take location.href, take pathname, split it and increment the last item with the value. Then join and assign to the pathname. Finally append the element to the body (or any other location).
Further readings:
Location all about <a>
document.location where you get the actuall href
var url = document.createElement('a'),
pathes;
url.href = 'http://example.com/123'; // or at the site: location.href
url.appendChild(document.createTextNode('link'));
pathes = url.pathname.split('/');
pathes[pathes.length - 1] = +pathes[pathes.length - 1] + 1;
url.pathname = pathes.join('/');
document.body.appendChild(url);

Related

Built relative URL in pages that are missing trailing slash /

We desperately need help with writing a small code that allows you to take the current page URL and the parameter in the href="parm" and create the link by joining the two with a slash.
The reason we need to do this is because we need relative links to the current page. The CMS system that we are working removes trailing slash from the end of URL.
Which is a problem because if you are at a page
domain.com/fruit/apple
and create a link such as href="calories" or href="./calories"
it will point to domain.com/fruit/calories
Instead, we want it to point to
domain.com/fruit/apple/calories
Which is relative to the current page.
We don't want to change the way that our CMS works, therefore, the need JS solution.
Below you can see one example of what we are trying to accomplish but this only works on one link.
link
Start JS
var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/"+ curHref);
End JS
The idea is to build relative links every time links with id="relurl" is used.
As per previous example this link: a href="home" id="relurl" target="_blank" title="This is a relative link!">link
at this page: domain.com/fruit/apple
it should point to domain.com/fruit/apple/home
Meaning the link structure is the currentpageURL + / + href
One page may have multiple relative links.
Thanks for any help.
While you could just use relative URLs in your links (with href="./page"), it sounds like the problem is that you are using duplicate IDs (which results in invalid markup). You can test that you have valid markup with the W3C Markup Validation Service.
When you have duplicate IDs, JavaScript only applies to the first element. This can be seen in the following:
var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/" + curHref);
Working Link
<br />
NOT Working
To resolve this, you should use classes instead of IDs for your links. You can then use document.getElementsByClassName to select the elements. Remember that this returns a NodeList collection of elements, so you'll need to set the new URLs inside of a loop, as can be seen in the following:
var x = window.location.href; // Current page URL
var links = document.getElementsByClassName("relurl"); // store the elements
for (var i = 0; i < links.length; i++) {
var curHref = links[i].getAttribute('href'); // Get HREF paramter
links[i].setAttribute('href', x + "/" + curHref);
}
Working Link
<br />
Another Working Link
Hope this helps! :)
This will update all links in the current page:
const updateNode = node =>
node.href = `${window.location}/${node.href}`
document.querySelectorAll('a').forEach(updateNode)

Reading the browser navigation bar and generating a navigational link based upon it

I'm wondering if it's possible to have a script that can read the address bar;
example (not an actual link): http://www.example.net/page-2011
and take the page-2011 part and turn it into
« Previous|Next »
So instead of having to make 3000 navigation links it just generates it automatically. As an additional challange the sidebar is a completely separate page, which is loaded at "compile time" for lack of a better term, when you load the page. http://www.example.net/nav:side This is the actual page that's pulled every time a page loads.
The Window.location read-only property returns a Location object with information about the current location of the document.
javascript Window.location
var url1 = window.location; //returns the url as an object
var url2 = window.location.href; //returns the url string
var url3 = window.location.pathname; //returns the url path
The split() method splits a String object into an array of strings by separating the string into substrings.
javascript .split()
Once you have the URL, you can use .split("-"). In your case, if every page is set as /page-2, this will return an object {"page","2"}
var pathSplit = url3.split("-"); //returns {"page","2"} from page-2
The slice() method extracts a section of a string and returns a new string.
javascript .slice()
In the event that your path ends with a /, you can use .slice() to trim off the last character.
var pathSplice = url3.slice(0,-1); //returns /page-2 from /page-2/
var pathSplit = pathSplice.split("-"); //returns {"/page","2"} from /page-2
Now you can grab the page number 2 by accessing the pathSplit object at index 1 and then parse the page number 2 as an integer and perform the required equations to receive the desired pages.
var pageNum = parseInt(pathSplit[1]);
var prevPage = 0,
nextPage = 0;
if(isNaN(pageNum) === false){
prevPage = pageNum - 1; //returns 1 from 2
nextPage = pageNum + 1; //returns 3 from 2
}
[Element.setAttribute()]Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
javascript .setAttribute()
Finally, you can set the value of your anchors <a></a> like so
var prevLink = document.querySelector(".prev-link");
var nextLink = document.querySelector(".next-link");
prevLink.setAttribute("href", "/page-" + prevPage.toString());
nextLink.setAttribute("href", "/page-" + nextPage.toString());
NOTE: Ensure you have assigned a class or id to your previous and next page links.

Redirect to random page (except the current page)

Solved! - didn't update my random number generation after changing from switch statement to array... ups. - Thanks!
Problem
Building a web comic and wanted to have one of those "random" buttons, where you jump to any of the strips. I'm assuming the best way to do this would be something on the back end (PHP or such), but I want to do it with JavaScript.
I got as far as picking a random page, but had the problem that it would sometimes redirect to the page it's already on (or rather often until I have more pages). I tried to make it take the page out of the array if the current page is the same as the target page, but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
I even made sure to use splice instead of delete. Doesn't that re-index the list?
Code
var pickRandomPage = function () {
// random Pages available
var links = [
"construction.html",
"placeholder.html",
"noplaymobil.html"];
// current Page
var currentURL = window.location.href;
var currentPage = currentURL.substr(currentURL.lastIndexOf('/')+1);
// get rid of current page from array of options
for(var i = 0; i < links.length; i++){
if(links[i] == currentPage){
links.splice(i,1);
}
}
// get a random number, rounded number between 0 and number of links
var randomPage = Math.floor((Math.random() * 3) + 1);
var link = 'http://bcitcomp.ca/students/hsloman/Comp1850/final/' + links[randomPage];
// open it
window.open(link,"_self");
};
Resources used sofar
Get current URL in web browser
window.open() should open the link in same tab
but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"
The undefined is because your randomPage variable will contain a number between 1 and 3, but the actual valid indices in your links array are only either 0 or 1 because it will only have two elements after you remove the current page URL.
Change:
var randomPage = Math.floor((Math.random() * 3) + 1);
to:
var randomPage = Math.floor(Math.random() * links.length);
put this right before the window.open(...) line:
if(link === window.location+"") return pickRandomPage();
This is saying, "if the chosen link is the page we're already on, run the function again" ..so it will keep trying until a new page is given. This is easier than trying to splice the array.
See: recursion for more info.

How to change referrer link?

How to convert this link 1 to the destination link 2 with Javascript. The second link is the actual destination of the original link1.
Update: I am given the link in the first link form, but I want it in the second form because I need to get Ajax request with the second link form.
original link
actual link
You cannot extract the full link, because The Guardian provides a shortened URL. The best thing you can do is to extract the shortened URL using substr and then apply decodeURIComponent:
function extractFacebookUrl(u) {
u = u.substr(u.indexOf('l.php?u=') + 8); // remove before ?u=
u = u.substr(0, u.indexOf('&')); // remove after &
return decodeURIComponent(u);
}
var link = "https://www.facebook.com/l.php?u=http%3A%2F%2Fgu.com%2Fp%2F4dqfm%2Ffb&h=VAQHJLcqT&enc=AZPaThEaRTCX-l4-p7IhnG-fLwffa6Gc29biVbxjLL_bwGigUa4xy6V1OwJKFCslcpd0qbSIDYtTBVOEovtYW2k2B37re6-kaQuraywUr_DNQcEm5MG8Cc9ODb8hfOZ5CuNoTYvIT7VxpMSwHDS1k-eChZ9vc3USJLAsoB0ZmFBOZmFQKd6o8n_SKadD6295xn5d6Q7_URlDDqw-7pjapUuZ&s=1";
document.body.innerText = extractFacebookUrl(link);
It returns http://gu.com/p/4dqfm/fb, which leads to the actual page.
Note that it supposes that original link has always the same format and the order of GET arguments.

Button/link to redirect up or down a level

I have two different levels within my site, but each have a similar structure. For example:
http://example.com/demo/insights.html
and
http://example.com/demo/complete/insights.html
What I'd like to do is add a link/button that the user can click to go up or down a level depending on where they are. The last part of the URL (e.g., insights.html) would stay the same. It's just whether or not the directory would change up or down.
So, if I'm on http://example.com/demo/insights.html, there would be a button to get to http://example.com/demo/complete/insights.html. If I was on http://example.com/demo/complete/insights.html
then there'd be a button to get to http://example.com/demo/insights.html.
I have a lot of pages like this, but I'd like to avoid hand-coding links on every page. I'm looking for something using javascript/jquery that will evaluate the directory level and the last part of the URL and redirect accordingly.
Any insights would be appreciated.
window.location.href
will give you the url of the page you are on, from there its just a matter of splitting split() the location and add/remove the required url substring
you can then add the new url into a common 'a' tag's href property on the page
As a rough example
var loc = window.location.href,
someSplits = loc.split("http://example.com/demo/"),
//you can do better reg ex, this is just quick
page = someSplits[1]; // this will give you the remaining url
// OR just replace the part you dont want
var loc = window.location.href,
page = loc.replace('http://example.com/demo/', '');
// this will give you the remaining url
One way to do this is to count slashes:
var link = window.location.href;
var deep = link.match(/\//g).length - 3;
var chunks = link.split(/\//);
if (deep) { // level 2
link = chunks[0] + '//' + chunks[2] + '/' + chunks[4]; // get rid of one level (chunks[3])
} else { // level 1
link = chunks[0] + '//' + chunks[2] + '/extra-level/' + chunks[3]; // add a level
}
You can use this:
location.assign('../'+location.pathname.substring(location.pathname.lastIndexOf("/") + 1))

Categories