QNA > H > How To Make A Hyperlink To Link With A Div

How to make a hyperlink to link with a div

Short answer:

  1.  
  2. link text 
  3.  
  4.  
  5. Div to go to
     

Works for any visible element, doesn't need to be a div.

Also works if you link it from an external page or site
(e.g. https://www.example.com/#id-of-div)

However, the scroll jump will be jarring and instant. If you're looking for a smooth scroll, you'll need to add some JavaScript.

Long answer

Add this to your document, before the closing body tag, in addition to the first code snippet.

If you already use jQuery, you don't need to include the jQuery file again. This script hooks on to a tags with the href attribute starting with # (like the example above) and modifies the default scroll to behaviour.

Note: External pages using the # bookmark link will still follow the default jump behaviour.

  1.  
  2.  
  3.  
  4. $(function(){ //wait for document to load ready  
  5.  
  6. $('a[href^="#"]').click(function(e){ //select anchor links that start with # 
  7. e.preventDefault(); //prevent normal jump to anchor action  
  8.  
  9. var elementpos= $($(this).attr('href')).offset().top; //get position of element to scroll to. 
  10.  
  11. var speed = 400; //time, in milliseconds, for the scroll action to complete.  
  12.  
  13. $('html, body').animate({scrollTop: elementpos+ 'px'}, speed); //animate the scroll. 
  14. }); 
  15. }); 
  16.  

What this does :

  1. Find anchor links and attach a click event to it. (Selectors )
  2. Obtain element selector to move to using .attr()
  3. Find the position of the element using .offset()
  4. Animate the movement using .animate()

Additional Notes:

IDs should be unique; 2 elements in the same HTML document should not have the same id. If a duplicate ID is found, the browser will only navigate to the first matching ID it finds.

Some older articles and answers might suggest using the name attribute on the a tag .

  1.  
  2. Div to go to
     
  3.  

Do note that this standard has been made obsolete by the latest W3C HTML5 standards (https://www.w3.org/TR/html5/obsolete.html#attr-a-name)
[I’m using an example of a external page # bookmark here].

This was how things were done in older versions of HTML (a decade ago). However browsers are not obliged to support this method, and it may be removed in future browser releases, hence the use of this method is highly discouraged.

Edits:

Placed more information about using external page links, as well as the unique ID criteria.

Adding World Wide Web Consortium (W3C) reference regarding obsolete method.

Di Pelligrini Swatt

Si può guardare la TV con gli occhiali VR? :: Qual è il modo migliore per trasmettere la TV in diretta?
Link utili