anchor jumping by using javascript - javascript

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
Okay, if you will click one of the links the url will automatically change to
www.domain.com/page#1
At the end this should be just:
www.domain.com/page
So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
and calling that function with:
<a onclick="jumpto('one');">One</a>
what will be the same like before. It will add the hash to the url. I also added
<a onclick="jumpto('one'); return false;">
without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}​
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)

I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.

I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }

Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
One
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺

The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
el.addEventListener('click', function(ev) {
ev.preventDefault();
const href = ev.target.getAttribute('href');
const hashIndex = href.indexOf('#');
if (hashIndex !== -1) {
const hashPart = href.substring(hashIndex);
if (location.hash === hashPart) {
document.querySelector(hashPart).scrollIntoView();
}
else {
location.hash = hashPart;
}
}
})

Related

Replace part of href with jQuery

I've read the other questions about this same topic, and I feel like I understand what to do, but it's not working.
I have two domains, out of necessity. On one specific page, I'm trying to update the links so that they point to the second domain. It functions if I just loop through every 'a' element, but not if I try to match specific links. I left my first attempt commented out, I'm not sure which method is better.
This function gets called if one is on that particular page, but are from a different country. I can't see what I'm doing wrong.
I thought that this.href should get the full, qualified URL but it doesn't seem to be doing so.
function updateLinksToUSAstore() {
$('a[href*="manitobahdev.myshopify.com"]').each(function() {
// $(this).attr('href', $(this).attr('href').replace('manitobahdev.myshopify.com', 'manitobahdev-us.myshopify.com'));
this.href = this.href.replace('manitobahdev', 'manitobahdev-us');
});
var CountryName = localStorage.getItem('CountryName');
// Change currently selected country text
$('#country-label, #country-label-mobile').text(CountryName);
}
Try it like this:
var href = null;
$("a").each(function()
{
href = $(this).attr("href");
if(href.contains("manitobahdev.myshopify.com"))
{
$(this).attr("href", href.replace("manitobahdev.myshopify.com", "manitobahdev-us.myshopify.com"));
}
});
I'm on mobile right now, so i was not able to test this. Sorry if it doesn't work.
Plus, i don't really understand why you'd want to edit only the manitobahdev part to manitobahdev-us, since both end with myshopify.com
May be it will help you.
//get all selector
var celem=jQuery('a[href*="manitobahdev.myshopify.com"]');
for(var i=0;i<celem.length;i++){
console.log('====== BEFORE ====');
//get each href of selector
var ele=jQuery(celem[i]).prop('href');
console.log(ele);
jQuery(celem[i]).prop('href',ele.replace('manitobahdev','manitobahdev-us'));
console.log('====== AFTER ===');
ele=jQuery(celem[i]).prop('href');
console.log(ele);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id='test1' href="manitobahdev.myshopify.com/ABC">Test 1</a>
<a id='test2' href="http://manitobahdev.myshopify.com/ZAXC">Test 2</a>
<a id='test3' href="manitobahdev.myshopify.com/USER/1">Test 3</a>

Chrome ignoring hashes in URL

I've spent quite a while trying to find answers for this issue, but haven't had any success. Basically I need to scroll the user to the contact portion of the website when they go to healthdollars.com/#contact. This works just fine in Safari, but in Chrome I haven't had any luck. I've tried using jQuery/Javascript to force the browser to scroll down, but I haven't been able to.
Does anyone have any ideas? It's driving me crazy - especially since it's such a simple thing to do.
Not a full answer but in Chrome if you disable Javascript I believe you get the desired behavior. This makes me believe that something in your JavaScript is preventing default browser behavior.
It looks to me like the target element doesn't exist when when page first loads. I don't have any problem if I navigate to the page and then add the hash.
if (window.location.hash.length && $(location.hash)) {
window.scrollTo(0, $(location.hash).offset().top)
}
check for a hash, find the element's page offset, and scroll there (x, y).
edit: I noticed that, in fact, the page starts at #contact, then scrolls back to the top. I agree with the other answerer that there's something on your page that's scrolling you to the top. I'd search for that before adding a hack.
You can do this with JS, for example` if you have JQuery.
$(function(){
// get the selector to scroll (#contact)
var $to = $(window.location.hash);
// jquery animate
$('html'/* or body */).animate({ scrollTop: $to.offset().top });
});
The name attribute doesn't exists in HTML 5 so chrome looks to have made the name attribute obsolete when you use the DOCTYPE html.
The other browsers have yet to catch up.
Change
<a name="contact"></a>
to
<a id="contact"></a>
Maybe this workaround with vanilla javascript can be useful:
// Get the HTMLElement that you want to scroll to.
var element = document.querySelector('#contact');
// Stories the height of element in the page.
var elementHeight = element.scrollHeight;
// Get the HTMLElement that will fire the scroll on{event}.
var trigger = document.querySelector('[href="#contact"]');
trigger.addEventListener('click', function (event) {
// Hide the hash from URL.
event.preventDefault();
// Call the scrollTo(width, height) method of window, for example.
window.scrollTo(0, elementHeight);
})

Function to find string on page and click link next to it?

I'm wondering whether it is possible to devise a script which will search a webpage for a certain string of text, and then click the link in the element id directly to its right.
Is this possible. Maybe javascript, php?
Please help, and thanks to all that do. :)
#Four_lo
Thanks for your reply. I'm sorry, maybe it's because I'm pretty new to javascript, but I can't really understand anything on the page you suggested.
I put together some javascript which will search the page for an element id and click the link within there.
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
I WANT TO CLICK HERE!
</body>
</html>
So basically, I need to search the page for GO HERE. Then, once this is found, I need to click the link in id="thisone", if that makes sense.
The above code works, and clicks the link within the id specified. However, I'd like to find certain text within that id, then move onto the next id, and click the link within that id.
It is possible. It will probably take some finesse but here is where you should start to access String you need. I believe regular expressions will be a must as well.
http://dom.spec.whatwg.org/#processinginstruction
http://domparsing.spec.whatwg.org/
Slightly more complicated than it needs to be:
function performAfterLinkWithText(text, perform) {
// get all the links
var $links = document.getElementsByTagName('a');
// scan them for your text
for(var i in $links) {
if($links[i].innerHTML === text) {
var $next = $links[i] // ready for loop
, terminateAfter = 20 // don't repeat forever
;
// keep checking the adjacent element
// because newlines show up as #text
do {
$next = $next.nextSibling;
} while( !$next.href && terminateAfter-- > 0 );
// do your thing
perform($next.href, $next); // window.location.href = $next.href;
}
}
}
// test -- performAfterLinkWithText('GO HERE', function(url, link) { console.log(url, link); });
performAfterLinkWithText('GO HERE', function(url) { window.location.href = $next.href; });
Or with jQuery:
window.location.href = $('a:contains("GO HERE")').next().attr('href')

Javascript substring method assistance

So long story short im working on a web app and using AJAX within it.
I'm trying to disable the default actions of links when clicked, attach a hash value to the link and then remove the "#" from the url.
the problem im having is that, although the hash values are being attached accordingly, the substring method isnt extracting the "#", it extracts the letter after it.....
here is my code. PS, i left my comments inthere so you get where im trying to go with this
so i dont know....my logic or setup may be wrong....
$(document).ready(function(){
//app vars
var mainHash = "index";
var menuBtn = $('.leftButton');
//~~~~~~load the index page at first go.
loadPage();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~menu show/hide
menuBtn.click( function(){
$('#menu').toggleClass();
});
//Menu items on click , disable link default actions.
$('#menu a').click( hijackLinks );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~functions for mobile index load AND hijacking app links to AJAX links.
function loadPage(url){
if( url == undefined){
$('#contentHere').load('index.html #content', hijackLinks);
window.location.hash = mainHash;
} else {
$('#contentHere').load(url + '#content', hijackLinks );
}
}
function hijackLinks(e){
var url = e.target.href;
e.preventDefault();
loadPage(e.target.href);
window.location.hash = $(this).attr("href").substring(1);
}
});
what im wanting is to remove the "#" from the url. What am i doing wrong, what am i not seeing/understanding?
ive tried substring/substr etc and both do the same thing in that no matter what numbers i choose to insert into the substrings params, they remove EVERYTHING BUT the "#" lol....
Thanks in advanced.
Well, you don't really change the link itself, you only change the window.location.hash, and the hash always has a "#" at the beginning.
What you need to do in order to change the entire url (and remove the '#') is to manipulate the browser history.
Although you should know it works only in newer browsers (the exact browser versions are in the link), so if you target your website to older too browsers you might need to think about having a fallback using the hash. If you decide to have such a fallback, I suggest searching for a plugin which does it instead of making it all yourself.

goto HTML document location dynamically

My page adds # to the html programatically and have this in the tag
function InsertTag(){
//Add <a name="spot"></a> to the middle of this document
}
window.addEventListener('load', InsertTag, false);
my question is how can I make the document then jump to #spot?
Here's a suggestion: use id's instead. If you have:
<div id="something">
Then page.html#something will take you straight to that div. It doesn't have to be a div, it can be used on any element. If you can manipulate the DOM to add that anchor, I am pretty sure you'll be able to do this.
Now... To get there, you can use:
// this approach should work with anchors too
window.location.hash = 'something';
// or scroll silently to position
var node = document.getElementById('something');
window.scroll(0, node.offsetTop);
See it in action here: http://ablazex.com/demos/jump.html
There are subtle differences between the methods. Eg: The first one will cause the location on the address bar to be updated, the second one won't.
If you want it to look nicer you can use a jQuery plugin, like ScrollTo.
Try
window.location = currentUrl+'#spot';
where currentUrl is a variable having the address of the current url
You can try this.
var el = document.getElementById('spot');
var eloffsetTop = el.offsetTop;
window.scroll(0,eloffsetTop);

Categories