How to jump to an element using JavaScript?

I am trying to move the page to a <div> element.

I tried the following code to no avail:

 document.getElementById("divFirst").style.visibility = 'visible'; document.getElementById("divFirst").style.display = 'block'; 
+114
javascript html
Feb 15 '11 at 18:02
source share
20 answers

You can use snapping to “focus” the div. I.e:

 <div id="myDiv"></div> 

and then use the following javascript:

 // the next line is required to work around a bug in WebKit (Chrome / Safari) location.href = "#"; location.href = "#myDiv"; 
+102
Feb 15 '11 at 18:08
source share

scrollIntoView works well:

 document.getElementById("divFirst").scrollIntoView(); 

full link in MDN docs:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

+168
Mar 10 '14 at 4:17
source share

your question and answers look different. I do not know if I am mistaken, but for those who googles and reach here, my answer will be as follows:

  • stack overflow
  • Similar question

The answer to my question is:

here is a simple javascript for this

call this when you need to scroll to the element with id = "yourSpecificElementId"

 window.scroll(0,findPos(document.getElementById("yourSpecificElementId"))); 

i.e. for the above question, if the intention is to scroll to the div with id 'divFirst'

the code will look like this: window.scroll(0,findPos(document.getElementById("divFirst")));

and you need this function to work:

 //Finds y value of given object function findPos(obj) { var curtop = 0; if (obj.offsetParent) { do { curtop += obj.offsetTop; } while (obj = obj.offsetParent); return [curtop]; } } 

the screen will scroll to your specific item.

+94
Aug 16 '12 at 11:44
source share

For Chrome and Firefox

I was a little versed in this, and I realized some kind of most natural way to do this. Of course, now this is my personal favorite scroll. :)

 const y = element.getBoundingClientRect().top + window.scrollY; window.scroll({ top: y, behavior: 'smooth' }); 

For proponents of IE, Edge and Safari

Please note that this is not supported in window.scroll({ ...options }) , not supported in IE, Edge and Safari. In this case, it is most likely best to use element.scrollIntoView() . (Supported in IE 6). Most likely, you can (read: not verified) pass parameters without any side effects.

Of course, they can be enclosed in a function that behaves in accordance with which browser is used.

+37
Apr 15 '18 at 13:17
source share

Try the following:

 var divFirst = document.getElementById("divFirst"); divFirst.style.visibility = 'visible'; divFirst.style.display = 'block'; divFirst.tabIndex = "-1"; divFirst.focus(); 

eg @:

http://jsfiddle.net/Vgrey/

+7
Feb 15 '11 at 18:08
source share

To jump to this element, just do it for javascript only.

Simple use:

 EPPZScrollTo.scrollVerticalToElementById('signup_form', 20); 

Engine object (you can play with a filter, fps values):

 /** * * Created by Borbás Geri on 12/17/13 * Copyright (c) 2013 eppz! development, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var EPPZScrollTo = { /** * Helpers. */ documentVerticalScrollPosition: function() { if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari. if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode). if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8. return 0; // None of the above. }, viewportHeight: function() { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; }, documentHeight: function() { return (document.height !== undefined) ? document.height : document.body.offsetHeight; }, documentMaximumScrollPosition: function() { return this.documentHeight() - this.viewportHeight(); }, elementVerticalClientPositionById: function(id) { var element = document.getElementById(id); var rectangle = element.getBoundingClientRect(); return rectangle.top; }, /** * Animation tick. */ scrollVerticalTickToPosition: function(currentPosition, targetPosition) { var filter = 0.2; var fps = 60; var difference = parseFloat(targetPosition) - parseFloat(currentPosition); // Snap, then stop if arrived. var arrived = (Math.abs(difference) <= 0.5); if (arrived) { // Apply target. scrollTo(0.0, targetPosition); return; } // Filtered position. currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter); // Apply target. scrollTo(0.0, Math.round(currentPosition)); // Schedule next tick. setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps)); }, /** * For public use. * * @param id The id of the element to scroll to. * @param padding Top padding to apply above element. */ scrollVerticalToElementById: function(id, padding) { var element = document.getElementById(id); if (element == null) { console.warn('Cannot find element with id \''+id+'\'.'); return; } var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding; var currentPosition = this.documentVerticalScrollPosition(); // Clamp. var maximumScrollPosition = this.documentMaximumScrollPosition(); if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition; // Start animation. this.scrollVerticalTickToPosition(currentPosition, targetPosition); } }; 
+6
Dec 18 '13 at 23:33
source share

Here's a function that may include an optional offset for these fixed headers. External libraries are not needed.

 function scrollIntoView(selector, offset = 0) { window.scroll(0, document.querySelector(selector).offsetTop - offset); } 

You can get the height of an element using jQuery and go to it.

 var headerHeight = $('.navbar-fixed-top').height(); scrollIntoView('#some-element', headerHeight) 

Update March 2018

Scroll to this answer without using jQuery

 scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight) 
+5
Jun 27 '17 at 17:41
source share

Well, I found this scrollToElement () function from src ripple :

 function scrollToElement(element) { var el = document.getElementById(element); var yPos = el.getClientRects()[0].top; var yScroll = window.scrollY; var interval = setInterval(function() { yScroll -= 10; window.scroll(0, yScroll); if (el.getClientRects()[0].top >= 0) { clearInterval(interval); } }, 5); } 

If you prefer, here is an alternative to findPos (object):

 function findPos(obj) { var curleft = 0, curtop = 0; do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return { left: curleft, top: curtop }; } 
+4
Feb 23 '16 at 15:28
source share

You can set focus on an element. Works better than scrollIntoView

node.setAttribute('tabindex', '-1')

node.focus()

node.removeAttribute('tabindex')

+3
Oct 22 '18 at 16:59
source share

Focus can only be set on interactive elements ... Div only represents the logical section of the page.

Perhaps you can set the borders around the div or change the color to simulate focus. And yes Visiblity is not the focus.

+2
Feb 15 '11 at 18:05
source share

I think if you add tabindex to your div, it will be able to get focus:

 <div class="divFirst" tabindex="-1"> </div> 

I do not think this is true, tabindex can only be applied to a region, region, button, input, object, selection and text area. But try it.

+1
Feb 15 '11 at 18:07
source share

Similar to @caveman solution

 const element = document.getElementById('theelementsid'); if (element) { window.scroll({ top: element.scrollTop, behavior: 'smooth', }) } 
+1
Aug 10 '18 at 10:33
source share

You cannot focus on a div. You can only focus on the input element in this div. Also, you need to use element.focus () instead of display ()

0
Feb 15 '11 at 18:07
source share

Looking around a lot, this is what finally helped me:

  • Find / find a div in your home that has a scroll bar. For me, it looked like this: "div class =" table_body table_body_div "scroll_top =" 0 "scroll_left =" 0 "style =" width: 1263px; height: 499px; "

  • I found it with this xpath: // div [@ class = 'table_body table_body_div']

  • JavaScript is used to perform scrolling as follows: (JavascriptExecutor)). ExecuteScript ("arguments [0] .scrollLeft = arguments [1];", element, 2000);

2000 is the number of pixels that I wanted to scroll to the right. Use scrollTop instead of scrollLeft if you want to scroll your div down.

Note. I tried using scrollIntoView but it did not work properly because there were several divs on my web page. It will work if you have only one main window in which attention is focused. This is the best solution I've come across if you do not want to use jQuery, which I did not want.

0
Aug 07 '15 at 5:34
source share

You can also use the location hash:

Add an identifier to the element:

 <div id="myElementId"></div> 

And then using JavaScript , change the URL hash:

 location.hash = 'myElementId'; 

I saw other solutions using location.href, but this seems a lot cleaner and does not change the whole url, only the hash.

0
Mar 08 '17 at 8:33
source share

The method that I often use to scroll a container to its contents.

 /** @param {HTMLElement} container : element scrolled. @param {HTMLElement} target : element where to scroll. @param {number} [offset] : scroll back by offset */ var scrollAt=function(container,target,offset){ if(container.contains(target)){ var ofs=[0,0]; var tmp=target; while (tmp!==container) { ofs[0]+=tmp.offsetWidth; ofs[1]+=tmp.offsetHeight; tmp=tmp.parentNode; } container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0)); }else{ throw('scrollAt Error: target not found in container'); } }; 

if you want to override globally, you can also do:

 HTMLElement.prototype.scrollAt=function(target,offset){ if(this.contains(target)){ var ofs=[0,0]; var tmp=target; while (tmp!==this) { ofs[0]+=tmp.offsetWidth; ofs[1]+=tmp.offsetHeight; tmp=tmp.parentNode; } container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0)); }else{ throw('scrollAt Error: target not found in container'); } }; 
0
Mar 10 '19 at 7:25
source share

Due to the behavior, "smooth" does not work in Safari, Safari ios, Explorer. I usually write a simple function using requestAnimationFrame

 (function(){ var start; var startPos = 0; //Navigation scroll page to element function scrollTo(timestamp, targetTop){ if(!start) start = timestamp var runtime = timestamp - start var progress = Math.min(runtime / 700, 1) window.scroll(0, startPos + (targetTop * progress) ) if(progress >= 1){ return; }else { requestAnimationFrame(function(timestamp){ scrollTo(timestamp, targetTop) }) } }; navElement.addEventListener('click', function(e){ var target = e.target //or this var targetTop = _(target).getBoundingClientRect().top startPos = window.scrollY requestAnimationFrame(function(timestamp){ scrollTo(timestamp, targetTop) }) } })(); 
0
Apr 16 '19 at 19:26
source share

The best, shortest answer that even works with animated effects:

 var scrollDiv = document.getElementById("myDiv").offsetTop; window.scrollTo({ top: scrollDiv, behavior: 'smooth'}); 

If you have a fixed navigation bar, simply subtract its height from the top value, so if your fixed bar height is 70px, line 2 will look like this:

 window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'}); 

Explanation: Line 1 gets the position of the element. Line 2 scroll to the position of the element; The behavior property adds a smooth animated effect.

0
Aug 01 '19 at 11:52 on
source share

If you want to use html you can just use this:

 a href="samplewebsite.com/subdivision.html#id 

and make an html link to a specific element identifier. Its main version is getElementById html.

-2
Nov 03
source share

try this feature

 function navigate(divId) { $j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500); } 

Pass div id as parameter that it will work I use it already

-2
Nov 03 '14 at 13:18
source share



All Articles