URL History.pushState + Scroll To Effect

I change the URLs of my sites to / name using History.pushState, which works, but the page does not view the location of the site where it is supposed to be.

index.php:

<nav> <ul> <li><a href="#work">Work</a></li> <li><a href="#about">About</a></li> <li><a href="#services">Services</a></li> <li>Blog <!-- Coming Soon... --> </li> <li><a href="#contact">Contact</a></li> </ul> </nav> <article class="content" id="work"> ... <article class="content" id="about"> ... 

jquery.page.js:

 _saveState = function( chapter ) { if (History.getState().url.queryStringToJSON().chapter !== chapter) { var page; if (chapter == 1) page = "/work"; if (chapter == 2) page = "/about"; if (chapter == 3) page = "/services"; if (chapter == 4) page = "/blog"; if (chapter == 5) page = "/contact"; else page = '?chapter=' + chapter; History.pushState(null, null, page) } }, ... _goto = function( chapter ) { var chapter = chapter || History.getState().url.queryStringToJSON().chapter, isHome = ( chapter === undefined ), $article = $( chapter ? '#' + 'chapter' + chapter : '#' + 'introduction' ); ... 

When a user clicks on a link in the navigation menu, how can I make the page go to the place that she suggested, as shown in the tutorial ? Do I follow him?

+4
source share
2 answers

History.getState().url.queryStringToJSON().chapter trying to find the chapter query parameter in your URL that no longer exists since you changed the format of the URL.

Without working with $ .History, it seems to me that you can try to compare with the url using something in the lines:

 if (History.getState().hash.replace(/^\/|\/$/g, '') !== chapter) { ... } // replace(/^\/|\/$/g, '') will remove a leading and/or trailing slash '/' 

Please note that if your site does not live in the root directory (for example, http://example.com/foo/bar/portfolio ), you still have to deal with the rest of the URL, as History.getState().hash will return you /foo/bar/portfolio instead of /portfolio .

(Note: if you click else if again, try switch instead.)

+2
source

theirs is not a problem in your javascript, its prefect, but the problem was in your html, please fix the content-wrapper shell that did not include articles that it was like

 <div class="content-wrapper"></div><article></article>... 

he should be

 <div class="content-wrapper"><article></article>....</div> 
+3
source

Source: https://habr.com/ru/post/1440449/


All Articles