How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL without reloading the page. What is the best way to detect if this URL changes?
- Is the
onloadevent called again? - Is there an event handler for the URL?
- Or must the URL be checked every second to detect a change?
In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the
hashchangeevent onwindow.In some old browsers, you need a timer that continually checks
location.hash. If you’re using jQuery, there is a plugin that does exactly that.Example
Below I undo any URL change, to keep just the scrolling: