'How I can I make jQuery go directly to <h2 id="id-name">?
I want to make jQuery navigates directly (no animation need) to a id that I pass in a variable.
I have various marks like id="content", id="edit", id="..." that are <h2> titles. Doing validation with PHP I will output a variable like var NAVIGATE_TO = <?php echo $where_failed;?> and I want to move the website to that id position.
Like if I do domain.tld/page#edit or #content but with jQuery because when I load the page my PHP framework doesn't allow me to indicate the hash.
Solution 1:[1]
You can set location.hash to the id you need the browser to scroll to:
window.location.hash = '#edit';
Solution 2:[2]
In my experience the window.location.hash solution only works once. If you don't want to use the plugin you could try this:
var navigationFn = {
goToSection: function(id) {
$('html, body').animate({
scrollTop: $(id).offset().top
}, 0);
}
}
and then call it like so (where someID is the ID of the element you wish to scroll to):
navigationFn.goToSection('#someID');
With this you can also vary the animation speed (I have it at 0) so that it is instant, but you could pass the value to the function so the code is reusable.
Solution 3:[3]
Use the jquery scrollto plugin then you can do it like this
$(document).ready(function(){
$(".topMenu").click(function() {
$.scrollTo($("#edit"), { duration: 0});
});
Solution 4:[4]
I know it's an old question, but I thought it would be also a good solution if just want the element to be visible in the browsers view. (scroll without any animation).
var elem = document.getElementById("yourContent");
elem.scrollIntoView();
The above sample is taken from https://www.w3schools.com/jsref/met_element_scrollintoview.asp
Solution 5:[5]
the question is for "jQuery"
with jQuery
@Patrick 's answer will be right and here is the example without function:
$('html, body').animate({scrollTop: $("#id").offset().top}, 0);
with javascript:
@Yi Jiang 's answer is javascript based
window.location.hash = '#idWithOrWithoutHashSign';
@Yusufbek answer works.
but why create variable?
instead:
document.getElementById("idWithoutHashSign").scrollIntoView();
also check difference with "smooth";
document.getElementById("idWithoutHashSign").scrollIntoView({behavior: "smooth"});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yi Jiang |
| Solution 2 | Patrick |
| Solution 3 | Kimtho6 |
| Solution 4 | Yusufbek |
| Solution 5 | sifr_dot_in |
