JQuery hashchange event - where to place?
You can trigger it manually like:
$(document).ready(function () {
$(window).on('hashchange', function () {
//do something
}).trigger('hashchange');
});
Or you can do it like:$(document).ready(function () {
//attaching the event listener
$(window).on('hashchange', function () {
//do something
});
//manually tiggering it if we have hash part in URL
if (window.location.hash) {
$(window).trigger('hashchange')
}
});
the hashchange event of jQuery doesn't work if I open a page with hash directly
You have to trigger the event manually on page load. The event will only get triggered when there is a direct action from the user.
Since it is page load with no action from the user the on hashchange event will not get triggered.
$(window).on('hashchange', function (e) {
alert(location.hash);
}).trigger('hashchange');
If you want to fire the event only when there is a hash value then$(window).on('hashchange', function (e) {
alert(location.hash);
});
if (window.location.hash) {
$(window).trigger('hashchange')
}
hashchange event not triggered with jquery in simple spa
Correct me if I am mistaken, but you are executing the function in your bind. You want it like this:
$(window).bind('hashchange', onHashchange).trigger('hashchange');
Without the '()' after.Bear in mind, the support of this is limited in some browsers.
Excerpt from: jQuery - hashchange event
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
Adapt according to your needs. jQuery hashchange event instantly executes animation with no speed
If you're changing a hash to an anchor that exists, it'll automatically jump to that anchor without waiting for the animation. You can see that this happens by just removing your animation since it still jumps. This can be fixed by using hashes in your URL that don't actually have an element with the corresponding id and changing your selector is scrollTop
to accommodate for this.
For example, you could change the id of an "about" section to be about-section
and continue to use #about
as the hash. Then instead of scrollTop: jQuery(window.location.hash).offset().top
, you'd use scrollTop: jQuery(window.location.hash + "-section").offset().top
to avoid the automatic jump to the element.
jquery: hashchange, prevent jumping to hash
problem is in your jquery.each block.
"return true" inside jquery.each block will not return but continue for next items.
Also, this will not return from your determineContent function, so the next code for scroll will also be executed and determineContent will always return false.
use a flag e.g.
var found = false;
JQuery.each(function(){
if(found) return;
//if your condition is true then found = true
})
if(found) return true;
//else continue the next line.
How to trigger an event when hash location changes
You should write 'hashchange' instead of 'onhashchange' in your first example.
This code works fine for me, at least in Chrome:
window.addEventListener('hashchange', function(e){
console.log('changed');
})
Here is short code-snippet:https://jsfiddle.net/bm8jjwmq/
How can I detect changes in location hash?
The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
$(window).on('hashchange', function() {
//.. work ..
});
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.
Related Topics
Getting a Union of Two Arrays in JavaScript
Why Are Exceptions Used for Rejecting Promises in Js
Using Fetch API to Access JSON
How to Parse a Date in Format "Yyyymmdd" in JavaScript
How to Calculate the Number of Years Between Two Dates
Es6 Classes:What About Instrospection
Conversion Between Utf-8 Arraybuffer and String
How to Add My Own Methods to HTMLelement Object
How to Take Advantage of Callback Functions for Asynchronous Xmlhttprequest
JavaScript Property with Three Dots (...)
Why Do I Need to Copy an Array to Use a Method on It
JavaScript Displaying a Float to 2 Decimal Places
Is There a Mechanism to Loop X Times in Es6 (Ecmascript 6) Without Mutable Variables
Twig Variable in External Js File
Can't Require() Default Export Value in Babel 6.X
Counting Frequency of Characters in a String Using JavaScript