GithubHelp home page GithubHelp logo

davist11 / jquery-one-page-nav Goto Github PK

View Code? Open in Web Editor NEW
1.5K 86.0 501.0 132 KB

Smooth scrolling and smart navigation when user scrolls on one-page sites.

Home Page: http://davist11.github.com/jQuery-One-Page-Nav/

License: MIT License

CSS 2.16% JavaScript 9.61% HTML 88.22%

jquery-one-page-nav's Introduction

A lightweight jQuery plugin for the navigation on one-page sites. Adds smooth scrolling when clicking on the navigation and automatically selects the correct navigation items as you are scrolling through the different sections.

The plugin still works even if you add additional content to the page after the fact that changes the position of each section.

Sample Markup:

<ul id="nav">
	<li class="current"><a href="#section-1">Section 1</a></li>
	<li><a href="#section-2">Section 2</a></li>
	<li><a href="#section-3">Section 3</a></li>
</ul>

<div id="section-1">
	<strong>Section 1</strong>
	<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

<div id="section-2">
	<strong>Section 2</strong>
	<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

<div id="section-3">
	<strong>Section 3</strong>
	<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

Example Usage with Defaults:

$('#nav').onePageNav({
	currentClass: 'current',
	changeHash: false,
	scrollSpeed: 750,
	scrollThreshold: 0.5,
	filter: '',
	easing: 'swing',
	begin: function() {
		//I get fired when the animation is starting
	},
	end: function() {
		//I get fired when the animation is ending
	},
	scrollChange: function($currentListItem) {
		//I get fired when you enter a section and I pass the list item of the section
	}
});

If you want the hash to change when a user clicks on the navigation, then change the changeHash options to true.

If you want to filter items out of your navigation then pass in a selector to the filter option.

Filter Example:

<ul id="nav">
	<li class="current"><a href="#section-1">Section 1</a></li>
	<li><a href="#section-2">Section 2</a></li>
	<li><a href="#section-3">Section 3</a></li>
	<li><a href="#section-4">Section 4</a></li>
	<li><a href="#section-5">Section 5</a></li>
	<li><a href="http://google.com" class="external">Some other link</a></li>
</ul>

$('#nav').onePageNav({
	filter: ':not(.external)'
});

Offset

In a previous version, there was an offset option to pass into the JavaScript. This was abandoned in favor of a CSS-only solution which simplified the code and makes it easier to handle responsively. Example

If you are having issues with iOS devices

If clicking a link in the nav makes the rest of the links unclickable until you scroll, you can solve it in this hacky way:

$('#nav').onePageNav({
	begin: function() {
		//Hack so you can click other menu items after the initial click
		$('body').append('<div id="device-dummy" style="height: 1px;"></div>');
	},
	end: function() {
		$('#device-dummy').remove();
	}
});

Found the solution here

jquery-one-page-nav's People

Contributors

davist11 avatar lolmaus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-one-page-nav's Issues

Cloned nav stops working

Hi,

i'm cloning my main navigation [ ('#sectionnav').clone(true).appendTo('#scrollnav'); ] to get a second, fixed position nav. $('#sectionnav, #scrollnav').onePageNav() works as long as i'm scrolling up and down the page. But after clicking on one of the element just this element keeps updating the current status.

Plugin not work in IE9

I'm checking out the demo and the smoothscroll and the active class toggle aint working.

Searching why.

Uncaught TypeError: Cannot read property 'top' of null

Hi Trevor,

I've been using and loving your plugin. But I stumbled across an issue earlier today. I can't even point to anything I did—the ScrollTop still works, jQuery still loads, but your plugin calls an UncaughtType Error. Just out of the blue.

I can make the error go away by adding a +1 to line 65—don't know why that happens....
topPos = (divPos +1).top;

I'm probably just going to start from scratch, but I wonder if its something I did or if its an error.

Full Error Text:

Uncaught TypeError: Cannot read property 'top' of null $.fn.onePageNav.onePageNav.getPositionsjquery.nav.js:65 e.extend.eachjquery.min.js:2 e.fn.e.eachjquery.min.js:2 $.fn.onePageNav.onePageNav.getPositionsjquery.nav.js:62 $.fn.onePageNav.onePageNav.initjquery.nav.js:102 $.fn.onePageNavjquery.nav.js:120 e.extend.eachjquery.min.js:2 e.fn.e.eachjquery.min.js:2 $.fn.onePageNavjquery.nav.js:116 (anonymous function)
And error screenshot: http://cl.ly/2d3A0j15372p3e1G4325

3.0 Features

  • Remove reliance on scrollTo plugin
  • Works both horizontally and vertically
  • Add class to section when it's active (to trigger animations)
  • Navigate between sections with keyboard
  • Support for multiple navigations
  • Zepto compatibility?
  • Items can be out of order.
  • Remove scrollOffset. Rely on CSS only solution.
  • Automatically select the first item when you are at the top of the page

Change URL hash on scrolling

Can one get the url to change when scrolling as it does when clicking on the links?
It is quite a big deal breaker when using hashtags as we want to make the page linkable.

possible to use on <a> 's with also a href="" for fallback?

Hey, I'm liking this plugin a lot. I'm currently using it on a site (not live yet) where I gave my <a> tag an ID so I could call it but when I add the href="#about" for a possible fallback solution the scrolling effect is not nearly as nice. So at the moment I have no fallback incase a user has JS turned off. my <a> tag is nested in nav - ul - li - a. Don't believe that matters though. Any thoughts?

External links handling in a mixed menu

I am using wordpress to populate a menu, and I have a language menu option (using wpml). The resulting html creates anchor links for the internal (scrollable) links and two links that lead to the same page like this:

http://[site]/[language]/

But when I enable the onepagenav plugin it does not go there (it looks for an internal link). I also tried to exclude them, but then they are not fired at all. What should I do?

how to change URL on scrolling ?

There is a option

changeHash: true

It works when we click on the item, means URL is updated on click but I wan to update URL on scrolling as well.
Is there any idea ?

Thanks.

Any plans for Zepto support?

Hi,

i really like that the plugins small size.

Any chance of making it compatible with Zepto in the future?

Good work.

How to add custom function on Nav click

Hi davist11,
I am using onePageNav for my personal website. I have fixed positioned header that changes when you scroll to next slide. It is updated by a function named updateHeader(); It works when I use the scroll bar and mouse wheel, but it does not work when I use the Nav.

I tried with:
self.$nav.on('click.onePageNav', updateHeader());

but it does not work. How can I call this function on Nav click?

Thank you for the great script and your time to answer my question.

Fails in Chrome when numbers are used for (some) anchor names

getSection apparently assumes a certain order in the sections object (top to bottom), however when numbers are used for some anchor names, the order is altered in Chrome.

Eg.:

#Logo
#1
#2
#3

becomes:

#1
#2
#3
#Logo

Since returnValue will take the last value in the sequence, this will break much of the functionality.

slide down after browser resize

Hi,

I am using your plugin for a project I am working on. I really like it alot.

I have one issue though. On my site I am building

In my 3rd and 4th sections (services and contact) on my site slide up when I resize my window to 480px width

but the top 2 sections do not ?

I am trying to use a responsive layout so I know thats at least part of it

but isnt this plugin supposed to reset to the corresponding id on browser window resize maybe it isnt

can I request that feature if it is not already available

here is the link of the page - http://theconfluencegroup.com/new_site/

let me know if I can clarify in any way and thanks for building this.

thanks again

Nick

current status

Hi,

I'm having an issue getting the navigation current status to work. The navigation style changes to current during the scroll down and scroll up. But does reverts back when the page stops on the section.

Oddly, when navigating backwards, the current status works correctly. The URL is below. Any help with this issue at all would be greatly appreciated. Thank you. Great plug-in.

http://184.173.252.168/~crdadmin/micro/

changeHash and scrollOffset conflict

With the latest files, if I set changeHash to "true," then the scrollOffset doesn't work. Basically, it scrolls to where it should be (i.e. with the scrollOffset), then snaps to the hash position (i.e. the top of the DIV or SECTION or what not). Unfortunately, can't figure out a way to make them both work together - I want the hash to change when I go to a section, but I also want the scrollOffset.

Scroll sections up/down using keyboard arrows

Hello,
I wonder if keyboard functionality can be added - to scroll sections up/down with the arrow keys? The code should look something like this:

$(document).on('keydown', function(e){
// up arrow = scroll up
if (e.keyCode == 38) {
// scroll to previous section
}
// down arrow, space = scroll down
else if (e.keyCode == 32 || e.keyCode == 40) {
// scroll to next section
}
});

I am not very experienced with jQuery. I face difficulties to do it on my own (tried whole Sunday). I will appreciate your help. Thank you.

Problem with Out of Order Menu Items

Thanks for the great plugin.

I have found a problem when menu items are out of order. For example if the last menu item was Top Of The Page, then the last menu item would always revert to current when manually scrolling, this would also happen when clicking the second last menu item.

In my implementation I have fixed this by altering getPositions and getSection to use the bottom as well as the top of the page section, as below:

   onePageNav.getPositions = function($this, o) {
      $this.find('a').each(function() {
        var linkHref = $(this).attr('href'),
            divPos = $(linkHref).offset(),
            topPos = divPos.top

        onePageNav.sections[linkHref.substr(1)] = {
                top: Math.round(topPos),
                bottom: Math.round(topPos)+$(linkHref).height()
        };
      });
    };


    onePageNav.getSection = function(windowPos) {
      var returnValue = '',
          windowCentre = Math.round($(window).height() / 2) + windowPos;

      for(var section in onePageNav.sections) {
          if (windowCentre >= onePageNav.sections[section].top &&
                windowCentre < onePageNav.sections[section].bottom) {
              return section;
          }
      }
    };

Hope this help.

bug on Android browser

I test the demo in the Android browser and found a bug. Not working class assignment "current". The changes are visible only after refreshing the page

Ipad issues with offset

Hi,

I'm using OnePageNav on a responsive site, so I want to make it work on an iPad. Unfortunately I come across the following problems:

The ScrollOffset is set to 80. When I click on a menu-item it scrolls to the right position, but then the offset kicks in, and it scrolls 80px down. But it also moves my navigation-bar with it. So instead of having a navigation-bar that's fixed to the top, it has a top margin of 80px.

For an example, you can check here: http://harper.level-devel.com

Also, it would be nice that the offset would be calculated before the page scrolls. I think the current effect is kind of weird. Is such thing possible?

ipad scrolling problems

I am having problems with scrolling animation on an ipad. The page flickers while it scrolls. I tried changing different settings, but can't get it to scroll smoothly. Thanks for your help

Getting error: TypeError: $(...).offset(...) is undefined

I'm using the js files straight from your demo on this menu (nested links, and filtering out the child links doesn't resolve it):

<ul id="menu">
    <li class="current"><a href="#Executive_Summary_1.0">1.0 Executive Summary</a>
        <ul>
            <li><a href="#Objectives_1.1">1.1 Objectives</a></li>   
            <li><a href="#Keys_to_Success_1.2">1.2 Keys to Success</a></li> 
            <li><a href="#Mission_1.3">1.3 Mission</a></li> 
        </ul>
    </li>
    <li><a href="#Company_Summary_2.0">2.0 Company Summary</a>
        <ul>
            <li><a href="#Company_Ownership_2.1">2.1 Company Ownership</a></li> 
            <li><a href="#Start-up_Summary_2.2">2.2 Start-up Summary</a></li>   
        </ul>
    </li>
    <li><a href="#Products_3.0">3.0 Products</a></li>
    <li><a href="#Market_Analysis_Summary_4.0">4.0 Market Analysis Summary</a>
        <ul>
            <li><a href="#Market_Segmentation_4.1">4.1 Market Segmentation</a></li> 
            <li><a href="#Industry_Analysis_4.2">4.2 Industry Analysis</a>
                <ul>
                    <li><a href="#Competition_and_Buying_Patterns_4.2.1">4.2.1 Competition and Buying Patterns</a></li> 
                </ul>

            </li>   
        </ul>
    </li>
    <li><a href="#Strategy_and_Implementation_Summary_5.0">5.0 Strategy and Implementation Summary</a>
        <ul>
            <li><a href="#Competitive_Edge_5.1">5.1 Competitive Edge</a></li>   
            <li><a href="#Marketing_Strategy_5.2">5.2 Marketing Strategy</a></li>   
            <li><a href="#Sales_Strategy_5.3">5.3 Sales Strategy</a>
                <ul>
                    <li><a href="#Sales_Forecast_5.3.1">5.3.1 Sales Forecast</a></li>   
                </ul>
            </li>   
        </ul>
    </li>
    <li><a href="#Management_Summary_6.0">6.0 Management Summary</a>
        <ul>
            <li><a href="#Personnel_Plan_6.1">6.1 Personnel Plan</a></li>   
        </ul>
    </li>
    <li><a href="#Financial_Plan_7.0">7.0 Financial Plan</a>
        <ul>
            <li><a href="#Important_Assumptions_7.1">7.1 Important Assumptions</a></li> 
            <li><a href="#Break-even_Analysis_7.2">7.2 Break-even Analysis</a></li> 
            <li><a href="#Projected_Profit_and_Loss_7.3">7.3 Projected Profit and Loss</a></li> 
            <li><a href="#Projected_Cash_Flow_7.4">7.4 Projected Cash Flow</a></li> 
            <li><a href="#Projected_Balance_Sheet_7.5">7.5 Projected Balance Sheet</a></li> 
            <li><a href="#Business_Ratios_7.6">7.6 Business Ratios</a></li> 
        </ul>

    </li>
    <li><a href="#appendix">Appendix</a></li>
</ul>       

I can see where var topPos; is being defined on line 115... but this error is still thrown.. any ideas as to why?

I have also tried removing the nested UL's from the nav, making it a single level menu.. which did not resolve anything.

I moved the var topPos; into the self.$nav.each(function() { function on line 117 to see if it needed to be declared within that function (just a shot in the dark, as it was globally defined within the parent function)... no dice.

Not sure if I've laid out the JSFiddle exactly as I have it... but, hopefully this will help:
http://jsfiddle.net/7Df88/

Thanks again and great work on the plugin !!

Change class of currently selected section

I'm trying to change the CSS class of the <li> as you scroll down the page or click the link in the nav, but it's not working for me. Either it's not working or I'm doing it wrong. Not sure if this is an issue or a fail on my part. Any input?

Remove and Add class only when necessary

Before calling onePageNav.adjustNav at line 80, check if element already has class with:

if(!($this.find('a[href=#'+position+']').parent().hasClass(curClass)))

another uncaught typeerror: cannot read property 'top' of null plugins.js:223

Hi,

I originally just dropped your plugin into my code and it worked beautifully, I only noticed this was happening when I tried to implement a bit more js code using jquery, and basically nothing was happening.

The site is on my localhost at the moment but Id be happy to send you the html and css. Im new to github so not sure best way of pinging that across to you.

the full error was as below -
Uncaught TypeError: Cannot read property 'top' of null plugins.js:223
OnePageNav.getPositions plugins.js:223
e.extend.each jquery.min.js:2
e.fn.e.each jquery.min.js:2
OnePageNav.getPositions plugins.js:221
OnePageNav.init plugins.js:171
$.fn.onePageNav plugins.js:311
e.extend.each jquery.min.js:2
e.fn.e.each jquery.min.js:2
$.fn.onePageNav plugins.js:310

That line turns out to be the last line of this bit:
self.$nav.each(function() {
linkHref = self.getHash($(this));
ie here--> topPos = $('#' + linkHref).offset().top;

Thanks for any help you can offer

Cloned nav stops working

Hi,

i'm cloning my main navigation [ ('#sectionnav').clone(true).appendTo('#scrollnav'); ] to get a second, fixed position nav. $('#sectionnav, #scrollnav').onePageNav() works as long as i'm scrolling up and down the page. But after clicking on one of the element just this element keeps updating the current status.

jquery 1.8

hi this is not working in jquery 1.8
thanks
mikul

Broken with nested lists

Hi,

Sorry I haven't set up my github account properly, so I can't write a formal pull request.

Anyway, it looks like the plugin is broken when using nested lists in the navigations (sub-<UL>s inside <LI>s).

I guess the line 28 of jqueyr.nav.js :
this.$nav = this.$elem.find('a');

should be changed into
this.$nav = this.$elem.children('li').children('a');

so it handles only the links from the main <LI>s, not the inside ones.

Hope it makes sense,

Regards :)

Issues with horizontal site

I'm not the best with jquery, so bear with me.... but I'm trying to make a horizontal site but when using the plug in it does not animate the scroll/slide to the indicated div. Is there something I need to change to make it work horizontally

Mixed menu items (Scroll & External Links)

If you want to use external links in the menu you generate, this causes a

 TypeError: topPos = $('#' + linkHref).offset().top; is undefined
 /one-page-nav/jquery.nav.js
 Line 119

Also external links are not clickable.

Offset option for ScrollTo

I added offset option for One page nav plugin. Maybe this option will be useful for somebody

For minified version

1) Find:

e.fn.onePageNav.defaults={currentClass:"current",changeHash:false,scrollSpeed:750,begin:false,end:false}

And replace to:

e.fn.onePageNav.defaults={currentClass:"current",changeHash:false,scrollSpeed:750,begin:false,end:false,scrollOffset:false}

2) Find:

e.scrollTo(h,a.scrollSpeed,{onAfter:function(){if(a.changeHash)window.location.hash=h;i.bind("scroll.onePageNav",function(){c.scrollChange(d,a.currentClass)});a.end&&a.end()}})

Replace to:

e.scrollTo(h,a.scrollSpeed,{onAfter:function(){if(a.changeHash)window.location.hash=h;i.bind("scroll.onePageNav",function(){c.scrollChange(d,a.currentClass)});a.end&&a.end()}, offset:a.scrollOffset})

Using:

$('.menu').onePageNav({currentClass: 'current', scrollSpeed: 10, scrollOffset:{top: -30, axes: 'y'}});

or

$('.menu').onePageNav({currentClass: 'current', scrollSpeed: 10, scrollOffset:-30});

Cannot read property 'top' of null

Hi,

I want to use One Page Nav on another project, but I'm getting the same "Cannot read property 'top' of null" error that I got the last time (a few issues ago).

I've put the files here so you can have a look: http://singlepage.waterstreetgm.org/stor.html

If you have any ideas I'd appreciate it - there's obviously something I'm not doing right if this has happened now 2-3 times in different projects. The code is here: https://github.com/saltcod/ui-elements

Help very welcome.

Thanks

Two nav for one navigation...

Hi, sorry for my bad english, i've a question for ur plugin.
Im a newvbie in jQuery and i've used ur plugin for my website.
In my website i've a two nav

Example:
< nav1>< ul>< li_5></ ul>
< logo>
< nav1>< ul>< li_5></ ul>

If i click in a voice list in nav1 and i click one voice in nav2 dont change, this plugin applyes a class in all nav...

Thanks.

Why does navigation order matter?

Very nice and usefull PlugIn!!

Independence of the order of links in the navigation would be great.
E.g. at the moment when I change the position of link 3 and 4 in navigation and scroll down to section 4 the PlugIn still adds the currentClass to link 3 instead of link 4.

thank you!

Horizontal Page

Hi,

I saw your blog and was trying to figure out how to apply it to my page that has horizontal scrolling.

I am super new to jquery & coding and was would love some help.

here's my page: universalpartnership.org/index_redo4.html

Am wondering where to put what for your plugin like the link to the plugin should be in the head or at the bottom of the body (like another scroll effect on the page) and what jquery script to put where.

Also, how can I have the left be at a particular page coordinate instead of top 0 & left 0?

thanks in advance!

curClass is not cleared on sections outside the navigation

When you have a section on the page that is not in the navigation, the curClass isn't removed.

Try adding <div style="height:2000px;">hello</div> at the top of #container in the example. Now when you scroll down the menu items change as expected. But when you scroll back to the top of the page, it shows that the current item is section 1 even though we've clearly scrolled above it. In this case none of the menu items shouldn't have curClass.

Wrong currentClass on reload (changeHash: true) in firefox

When changeHash is enabled and I reload the page viewing a section:
-> In Chrome on reload the related navigation link gets the currentClass.
-> In Firefox on reload the currentClass is always on first navigation link, independent of which section I'm viewing.

Multiple Navigations

I have inline jump-to links (look for class .quicklink), which do not work on a second click. I'm assuming this is probably a quick fix, but am not sure how to rectify it.

Any suggestions appreciated. Thanks!

Internal Links

Does the plug-in support links within the page to jump from point to point? As far as I can tell they need to be grouped in a navigation as in multiple.htm.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.