I want something that is so close to the thing we have in stackoverflow. Consider i have a page like this : "myPage.com". then consider that after a search i want to redirect the user to this page but exactly on the desired element, like this : "myPage.com#123". As you know the "123" is the id of the element i want the page to scroll to it. but the thing is that scrolling is not enough. I want to do additional jobs with JQuery and i want to know how can i add event handlers to this. And being more direct, what is this event?
Asked
Active
Viewed 50 times
2 Answers
1
You can add an event listener to the load event. and then get the Anchor (the #123) and then do whethever you want with it.
For the scrolling, the #123 is enough for the browser to understand what you want.
1
Simplest way to do that is to check hash on document ready like this:
$(function() {
// assign value of hash to hash variable
var hash = window.location.hash;
// check if hash isn't undefined
if (hash) {
// target element with id from hash
var $where = $(hash);
// animate scroll to position of element from hash
$('html, body').animate({ scrollTop: parseInt($where.position().top) + 'px' }, 300);
} else {
// there is no hash ;-)
alert('no hash');
}
});
There is also onhashchange event:
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange

Tomasz
- 106
- 1
- 7
-
This will be good at the page load but the thing is i will have an in page search! which will link to an id in the same page. this answer is good and i can handle the things manually but if is there any even of being notified of a hash, it will be better. thanks. – ConductedClever Jul 29 '15 at 02:48
-
Glad I could help ;-) – Tomasz Jul 29 '15 at 09:08