Getting Href From Hyperlink Text in Javascript/JQuery - javascript

I am trying to write a Tampermonkey script to help the navigation of some of the websites I commonly browse. The goal is to be able to browse through the pagination of the page with the arrow keys (for instance, if I am on page 3, left key would go to page 2). I want to be able to search the page to ensure the Previous link exists, and if it does, click it to go to the previous page.
An example would be as follows:
<a href="www.example.com/page/2.html>Previous</a>
Instead of parsing the url to get the "2" as an integer, incrementing or decrementing as needed, and reconstructing the url, I want to find the word "Previous" and click it if it exists. How would I go about doing this? Thank you much for your time!
This is somewhat what I am looking for:
http://runnable.com/UhZCuuHhSAsoAALM/how-to-get-a-href-value-using-jquery
However, the code uses
var href = $('a:first').attr('href');
to get the first href on the page. I need it to get a specific href on the page (one titled "Previous").

Moving backward and forward through the user's history is done using the back(), forward(), and go() methods.
window.history.back();
window.history.forward();
Check out MozDev

<body id="body" data-page='2'>...
javascript
var num = document.getElementById('body').getAttribute('data-page');
document.onkeyup = function(e) {
if (e.keyCode == 37) {
window.location.href = "www.example.com/page/"+(num-1)+".html";
}
if (e.keyCode == 39){
window.location.href = "www.example.com/page/"+(num+1)+".html";
}
};
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Related

How to detect redirection to the same address when using hash navigation?

This question is sort of what i'm thinking, but has no answers.
I have successfully implemented hash navigation in my application using the following code:
$(window).on('hashchange', function () {
loadContent(location.hash.slice(1));
}).trigger('hashchange');
I use this event to download partial HTML content from the server via Ajax, and it gets called when the browser detects a change on the hash in the address bar. The addresses looks like this:
https://www.mywebsite.com/#/account/login
The problem is, when the link is the same it does not fire the hashchange event (for obvious reasons). I need to call the function loadContent to refresh the page.
For example, before I implemented hash navigation, if the user wanted to discard all the changes he made to the page, he simply clicks the same link in the system menu, or click the address bar and hit enter. Then, the browser will redirect to the same page and drop all the changes.
But now, I can't detect that. What can I do to detect those commands and call my loadContent(location.hash.slice(1)); function?
After some research, I come to conclusion that there's no way to do that. I found this question that is very close to mine, but also no useful answer, other than handling the "onclick" event on every link on the site. Not a very beautiful solution - and does not solve the functionality of hitting enter on the address bar.
I ended up with a different approach. Definitely does not solve the way I wanted, however I think that it's more elegant from code perspective and practical from user perspective. I created a keyboard shortcut to refresh the page:
function doc_keyUp(e) {
if (e.altKey && e.keyCode === 82) { // ALT + R
if (confirm("Discard changes and refresh the page?")) {
loadContent(location.hash.slice(1));
}
return false;
}
}
document.addEventListener('keyup', doc_keyUp, false);
It may a simple approach, but what if you store your current hash in a property and afterwards register a click event and check if the hash is still the same?
Here is an (untested) example. But you should get the idea.
var storedHash = document.location.hash;
// You may add a data attribute to corresponding links to not
// catch all 'a'-tags (i.e. document.querySelectorAll('a[data-nav=true]'))
var links = document.querySelectorAll('a');
for (var i in links) {
if (!links.hasOwnProperty(i)) {
continue;
}
links[i].addEventListener('click', function() {
if (document.location.hash === storedHash) {
// Here comes your logic
}
});
}

JQuery: Why won't the website open?

I'm sort of new to JQuery, but I'm practicing everyday. My goal is to open the link after the buttons have been clicked but the link doesn't seem to be opening. I'm trying to open the link inside the if statement so everything happens accordingly.
window.setInterval(function(){
if ($('#add-remove-buttons').find('.button').length > 0) {
$('#size').val($('#size option').filter(function(ind, el) {
return $(el).text() === 'Large';
}).val());
$('#add-remove-buttons').find('.button').trigger('click');
setTimeout(function() {
window.location.replace('http://myweblink');
}, 900);
}
}, 100);
EDIT (STILL NEED HELP)
I've tried changing it but it doesn't load. I think it might be getting stuck in the 100ms loop. I put the function in a 100ms loop so it can detect if ($('#add-remove-buttons').find('.button').length > 0) I also just realized that after the user clicks the button, this html automatically appears:
<fieldset id="add-remove-buttons"><input class="button remove" name="commit" value="remove" type="submit">keep shopping</fieldset>
This means that the if statement : if ($('#add-remove-buttons').find('.button').length > 0) from my code, becomes false and the code for changing the URL doesn't run. Is there a way to detect the presence of the html code above like the if statement that became false? After I figure that out, I can put the window.location.href = "http://myweblink"; and then get it to work!
And in your code it is missing the complete web address.
Use
window.location.replace('http://myweblink.com');
Instead
window.location.replace('http://myweblink');
To redirect,jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
It is better than using window.location.href =, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
You can read the answer here.
Try
window.location.href = "http://your.wesite.com";
This will replace your address bar.
If you're using jQuery, just use $(location).attr('href',url);.
window.location.href seems to have inconstant behavior in some browsers, in fact, it flat out doesn't work in my version of Firefox.

Browser back button does not work for Anchor links

In the footer of my page there a few links that point to different sections on the same page using anchor tags (# appended to the URL of the page).
This works fine, just the browser back button does not work: I cannot move back to the previous page from where I had navigated to the anchored page.
The simple question here is, is it possible to move back to previous page after navigating in the anchored page a few times? If it is then please could you suggest how?
Anchored page: the page that has several sections marked by the id attribute that can be pointed to by a URL with #anchorId at the end.
I also faced the same problem see my question anchor links referring to the page sections not working on browser refresh, back and forward
But I had to do it the way normal links work so what I did was I manually go to that section by getting the element from the hash.
$(window).on('hashchange', function ()
{
var top = $(window.location.hash).offset().top;
$(window).scrollTop(top);
});
This works for forward and back buttons.
And for refresh also you need to do the same thing. Get the element from the hash and scroll to that element manually.
History and the Back Button.
In days of old, the back button did little more that go to the previous item in the browser's history. That's changed quite a bit since then, as it keeps its own history according to a somewhat simple set of rules. Good luck digging through standards docs to find it though.
UI/UX and why NOT to change expected behaviors.
Please reference w3c's 'don't brek the back-button before you go making changes to a browser's default behavior. Its like that for a reason, following mountains of debate and defining standards.
Ultimately, this is what browsers do, and so this is what the users expect. If you begin to subvert the behavior away from user's expectations, you're likely to start pissing off your users. When buttons and links repeatedly don't behave as expected, users will often just give up and leave your site.
Prevent Default.
If you really must alter the default behavior, the using javascript would be the best way to do it:
<a href="#id" onclick="return gotoAnchor(this);">
<script>
function gotoAnchor(elm) {
window.event.returnValue = false;
var url = location.href;
location.href = elm.href;
history.replaceState(null,null,url);
return false;
}
</script>
http://www.the-art-of-web.com/javascript/remove-anchor-links/
Visit that site. Scroll to the bottom and use test the anchors. It's doing what you want.
"The following code will parse your HTML page and override the function of any links that target anchor points on the same page. The link function will be replaced with a call to the scrollIntoView method of the target element:
document.addEventListener("DOMContentLoaded", function() {
var links = document.getElementsByTagName("A");
for(var i=0; i < links.length; i++) {
if(!links[i].hash) continue;
if(links[i].origin + links[i].pathname != self.location.href) continue;
(function(anchorPoint) {
links[i].addEventListener("click", function(e) {
anchorPoint.scrollIntoView(true);
e.preventDefault();
}, false);
})(document.getElementById(links[i].hash.replace(/#/, "")));
}
}, false);
if (document.referrer == "") {
window.open("index.php");
} else {
window.history.go(-1);
return false;
}

remember most recent click

So I want to be able to have a different styling for a link after you go to the page it's clicked on. I have been using the following code:
$(document).ready(function(){
var url = document.URL;
function contains(search, find) {
return search.indexOf(find) !== -1;
};
$('#topbar a').each(function(){
var link = $(this).attr('href');
var answer = contains(link,url);
if(answer === true){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
This goes through the links in my navigation bar and checks if it's on the same page as the link, and it works, but I can't use it in one specific case: Random.
I have a link that generates a random page from the pages I have, so it does not have a specified link as it links to a function to randomly generate the page (note: I cannot change the function or access information from it).
So how can I detect that the random link was clicked previously so i can give it the .check class
If i understand your question correctly, your function does not work for the randomlink because this has a href like http://mysite.com/random, but the server will actualy redirect you to a different page, like http://mysite.com/about-me, and therefore the url of the active page does not match the href of the random button, and it will not get the active state.
One could argue if you would want it to get the active state, cause clicking it again would not (likely) bring you to the same page, but that is besides the question.
I can see to ways to solve this.
server side:
In stead of redirecting to ie. http://mysite.com/about-me in the random function, you could also redirect to http://mysite.com/about-me?random. By adding this get variable, you should not change the behaviour of the link (unless you have some very strict controller, or that variable is actually used, but that is unlikely). You could then detect with javascript if that variable is present in the url, and then activate the random button.
Something like this:
$(document).ready(function(){
var url = document.URL;
// check for random
if (url.indexOf('?random') >= 0) {
$('#topbar a.random').addClass('check');
}
// check all other
$('#topbar a:not(.random)').each(function(){
if($(this).attr('href').indexOf(url) >= 0){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
cookie:
If you do not have acces to the server side random controller, you could do it entirely with javascript, by the use of a cookie (the only way I know to make a variable persist trough page requests).
On click of the random button, you would first set a random cookie to true with javascript, before letting the actual link do it's thing. On entering the page, you could then do a similar check as in my previous option, but in stead of the url you check if the cookie is tre. If so, you change it to false (so on the next page request the random button will not be active again) and set the randombutton to active.
As I believe the first solution is to be preferred (cookies should only be used as a last resort, they are sent on every page request, which means extra data, and your user might have cookies disabled, or there might be laws against using cookies, so the function could not always work), I will not write the javascript yet. Feel free to ask if you prefer this solution and need further help however.

perform href before onClick

I've the following link:
I
And this use the following javascript:
function showGallery(){
if(window.location.hash) {
$('#gallery').fadeIn('fast');
var hash = window.location.hash.substring(1);
alert(hash);
} else {
}
}
So it only show the gallery when in the URL is a hashtag. But when i click on the link, nothing happens. When i click it twice, the gallery fade in.
So the link first make the javascript, and i doesn't work 'cause there is no hashtag in the URL and after that, it perform the href and insert the Hashtag in the URL.
How can i do that?
My Target:
When i click on a link, it open a gallery. To know which gallery i must open, i insert in the URL a Hashtag. Here i want to display the HDR album. And i also want, if my site get opend with a hashtag, it should display the gallery.!
Is there also a another, easier or cleaner way to make it?
Hope you understand what i want.
For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:
I
And the Javascript is run whenever the hash has changed:
function locationHashChanged() {
if (location.hash === "#HDR") {
$('#gallery').fadeIn('fast');
}
}
window.onhashchange = locationHashChanged;
Have you tried a setTimeout call to delay the onclick event?
Like this:
I
You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.
<a onClick="showGallery('HDR')">I</a>
And then:
function showGallery(name){
if(name) {
$('#gallery').fadeIn('fast');
alert(name);
} else {
}
}
If you want to run showGallery() without following the link, the correct code is this:
I
By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.
In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.
You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.
What you can do is this:
gallery 1
function showGallery(galid){
var linkhash = $('#' + galid).attr('href').substring(1);
alert(linkhash);
$('#gallery' + linkhash).fadeIn('fast');
}

Categories