How to stop losing proper location/url when smooth scrolling to hash - javascript

Ok, I have a few issues... I'm building my site with bootstrap/jquery. I'm using bootstrap nav and all nav links are hash links to different containers on the same page.
Issue #1
When using the method below to 'hijack' the link I lose the URL address thus look the ability for people to grab the link and share or link to it later.
Issue #2
There are a few other pages with content that aren't on the homepage. So obviously when users click on the link /somepage/#photography doesn't work. Is the only solution here to not use relative links?
<nav>
Photography
</nav>
// smooth scroll from navigation
$('nav a').click(function(evt){
evt.preventDefault();
var $section = $($(this).attr('href'));
scrollToObject($section);
});

Issue 1: the reason for losing the hash at the end of the URL is because the call to evt.preventDefault() is preventing the hash from being added.
I am not 100% sure on the inner-workings of the scroll effect in scrollToObject(), but if you can provide a callback function when the scrolling is complete you could then add location.assign( evt.target.hash ); which will add the hash to the URL (and it will show up in the user's history.) Of course, you can get the hash value from the anchor object, event, etc.
You can read about the location interface in js on MDN here: https://developer.mozilla.org/en-US/docs/Web/API/Location
Issue 2: You could actually accomplish this once again using location.assign(). Once again, without seeing all of your code, you can create a conditional in a callback and then send the user back to the page with the scrolling anchors: location.assign( location.origin + '/' + evt.target.hash ).

Related

Navigate using Javascript, but change the URL

I want to navigate inside the page with an animation using Javascript, but also change the URL so the user can click "back" to go back to the previous "page".
I have no idea how to approach this. Do I put the content I'm navigating to on a new html page, or on the same page?
What I've tried so far:
Some Other Page
This will completely reload to someOtherPage, and won't allow animations.
Some Other Page
<script>
function animateToOtherSection() {
//things like fade in/out or scroll
}
</script>
This works if the content I'm navigating to exists in this page, which is okay, but the URL won't be changed (except for the additional #).
If i try to change window.href in Javascript, the entire page reloads, which is not desired.
This question was inspired by some websites like this. When the See our projects button is clicked, although it as an anchor element, the page doesn't reload, but a fade out/in executes and the navigation bar above stays throughout. If I click the 'back' button in my browser, another animation takes me back to the splash screen.
Note: This is not an option:
Some Other Page
I don't want to just scroll to an element, but manipulate and show/hide a lot of elements on the screen.
Thanks in advance for the answers!
The DOM window object provides access to the browser's history through the history object. It exposes useful methods and properties that let you move back and forth through the user's history, as well as -- starting with HTML5 -- manipulate the contents of the history stack.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
Load data from the server and place the returned HTML into the matched element.
http://api.jquery.com/load/
You can make it easy here is example:
HTML:
<button id="changeUrl">See our projects</button>
JavaScript:
$('#changeUrl').click(function () {
history.pushState({}, 'Title', '/Url/Test');
$(document).load('/url html');
});
Also you can add animation for example :
$('#changeUrl').click(function () {
$('body').fadeOut();
history.pushState({}, 'Title', '/Url/Test');
$(document).load('/url html', function () {
$('body').fadeIn();
});
});
You may also add a JavaScript "fadeout" animation when "unloading" the current page, and a "fadein" animation executing at the begining of the next page load.
If you prefetch most of your content, the transition will be smooth.
To avoid a page load when you click on a link, attach an onclick event to your link, and finish your JavaScript callback by a e.preventDefault(); as explained in this question : How to stop default link click behavior with jQuery from Mozilla Dev Network : https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable, without stopping further propagation of the event.
About link prefetching : https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ
<link rel="prefetch" href="/images/big.jpeg">
Or even really loading <img with a style=display:none; to hide them…

jQuery .load page then navigate to anchor using hashtag

I need help with a jQuery function that will allow me to use hashtags to scroll to an anchor point on a .load() page.
Basically someone clicks on a homepage link and it opens up a model window that they use to navigate the remainder of the website. This window then uses the same code to open up any other links on the site. I know the format of these links is not optimal, but it's what I am required to work with.
I have the following code that is displayed in a model window.
<div id="pop-top-menu">
<p class="p_text">
Go Back |
View by Resorts |
View our Private Homes |
View our Properties with Discount Coupons</p>
</div>
When someone clicks on one of those links, it will then go though this code:
function pop(id) {
$("#body-cover").fadeIn(1000);
$("#slide-content").load(id).slideDown(1000);
$("#slide-content-close").delay(2000).fadeIn(1000);
}
So I need to have the visitor click on properties.php#property_id and it load the page properties.php and THEN navigate to the anchor tag. Not all links will have anchors, but many will.
Please note, this is not anchor-based navigation. This is loading a link and THEN navigating to the anchor provided (if it exists).
Untested, but when I understood your question correctly you could modify your pop function like this:
function pop(id) {
// Expression to test if id has a hashtag
var hasHash = /(#([^ ]*)/,
$hashID;
$("#body-cover").fadeIn(1000);
$("#slide-content").load(id).slideDown(1000);
$("#slide-content-close").delay(2000).fadeIn(1000);
if(hasHash.test(id)!== false) {
// hasfound - grep it, and make a jQuery Object
$hashID = $('#' + id.split('#')[1]);
if($hashID.length) {
// if it is found, scroll to this element with an animation
// in case you just want a jump, simply set scrollTop
// and remove the animate method
$('html, body').animate({
scrollTop: $hashID.offset().top
}, 2000);
}
}
}

Effectively handling Browser history and Back button [duplicate]

I want to change the way that content is displayed on my website:
var FNav = {
init: function() {
$("a[href*=#]").click(function(e) {
e.preventDefault();
if($(this).attr("href").split("#")[1]) {
FluidNav.goTo($(this).attr("href").split("#")[1]);
}
});
this.goTo("home");
},
goTo: function(page) {
var next_page = $("#"+page);
var nav_item = $('nav ul li a[href=#'+page+']');
$(".page").fadeOut(500);
next_page.fadeIn(500);
How do I change this JavaScript, so I can have a proper back button functionality?
What I have tried (Unsuccessfuly). These are the solutions that I tried but without changing the javascript above. That is why I think none of them seem to work.
Using the History.js method described here:
https://github.com/browserstate/history.js/ I fill out all the steps and
enter the scripts to the header, however only the URL in the URL bar
changes when I click on a link. When I click the Back button, the URl
changes accordingly, but content doesn't load. When I enter a URL in
the URL bar, I get sent to the home page.
Ajaxify and Gist method
described here: https://github.com/browserstate/ajaxify Achieves the
same as above, same issues as well
Davis.js method described here:
https://github.com/olivernn/davis.js Achieves nothing upon completion
of the installation instructions. No change.
jQuery BBQ Plugin method
described here: http://benalman.com/projects/jquery-bbq-plugin/
Achieves nothing, no change upon loading the .js file in the header
of the website.
I read this article and understood it:
http://diveintohtml5.info/history.html
I'm not sure why you couldn't get Davis.js to work for you? Perhaps open an issue on the GitHub page.
If you want to use hash based routing with davis you need to include the hash routing extension. You then just need to include it in your page after davis.
The following setup should then allow you to handle routes
Davis.extend(Davis.hash)
Davis(function () {
this.get('/:page', function (req) {
FluidNav.goTo(req.params.page);
})
})
Assuming you have links in your page with the following
Page1
Page2
Davis will take care of handling the back button for you, so that if you click on the link for Page1 and then Page2, clicking on the back button will navigate to Page1 again.
If you have any problems please open an issue on the GitHub page detailing what you have and what isn't working and I can take a look at it.
The back button does not magically work. You need to code and listen for the event change!
In history.js, it shows you right on the front page:
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
History.log(State.data, State.title, State.url);
});

disable anchor tag

How would I go about putting a link on a page that changes the url, but doesn't change the page without using hash states?
I want to put links that change the url and scroll to a corresponding section of the page. I don't want to use hashes as they just jump to the section instead of scrolling, and I think hashes dont look very good in the url.
Take a look at HTML5 Push State
There is no other way as far as I know.
Have you tried the jQuery ScrollTo plugin? http://archive.plugins.jquery.com/project/ScrollTo
Browsers now have security features that ensure that the URL displayed in the location bar matches what's actually being displayed. You can't change the location without changing the page at the same time.
However, you can scroll the page anywhere you like without changing the URL. To scroll to a particular element, get its position and use .animate():
$('body').animate({scrollTop: $('#element').position().top});
​
Combine this with an .on('click',...) handler that uses e.preventDefault() to cancel the URL change and you're good to go.
$('a[href^=#]').on('click', function(e) { // apply to all hash links
var el = $(this).attr('href'); // get the href
e.preventDefault(); // cancel default click action
$('body').animate({
scrollTop: $(el).position().top // scroll to the href ID instead
});
});​
http://jsfiddle.net/mblase75/WFKUE/
HTML5 browser history (aka PushState) is the modern approach
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history
It is fairly widely supported in browsers
http://caniuse.com/history

JavasScript ping to top of page?

Is there a way to push the browser back to the top of the page when a link is clicked? I am dynamically changing some content but the project needs the user to start at the top of the page when the new content is loaded.
I am already using the url hash tag to keep track of the history. Just looking for some type of javascript function to do this.
What you probably want is scroll(0,0).
As a link:
back to the top
Or just the javascript itself (integrated in a function):
function onContentLoad() {
scroll(0,0);
}
For further reference:
http://developer.mozilla.org/en/window.scroll
http://msdn.microsoft.com/en-us/library/
inflagranti's answer is right about the way to do it using javascript.
If you use jQuery you can also animate the scroll to top action.
$('html, body').animate({scrollTop:0}, 'slow');
You could create an anchor at the top of the page wether it contain text or not.
Then on your link have to refer to the anchor.
Example:
Create an anchor:
<a name="tips">Useful Tips Section</a>
or
<a name="top"></a>
Then create a link to said anchor:
Visit the Useful Tips Section
or
Go to top.
Ta da.

Categories

Resources