简体   繁体   中英

using URL hashes in javascript AND anchors

We're using URL hashes in some places in our app to filter the display, eg #highlight=free will highlight our free content. We use javascript to process the hash, listen to hash changes. All works great.

We're wondering however about the best way to mix it with "real" HTML anchor links. ie links that point to a specific html id on the page, eg #chapter-5 .

Should we implement jumping to the right place using javascript and stop relying on the default browser behaviour? for example, link to #chapter=chapter-5&highlight=free and handle both filter and anchor in javascript? Or is there a safe/standard way to "mix" anchors and custom hashes?

If your target environment allows it, then the "safe/standard way" would be to leave hashes with old-school hash (commonly seen as "hashbang") approach alone for regular in-page anchors and use modern HTML5 history API instead .

If you must support older browsers you can use some polyfill that resorts back to that hash.

The comments to the question were probably the most helpful so far, and so we chose to implement anchor jumping and deal with everything after the # in javascript, and not rely on built-in support in browsers for it.

For those interested, we use a combination of jquery.deparam , URI.js and some custom code to listen to hash changes and hook into our own functions. We also played with Hasher.js which looked nice, so we might use it in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM