How to make a hyperlink to link with a div
Short answer:
- link text
- 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.
- $(function(){ //wait for document to load ready
- $('a[href^="#"]').click(function(e){ //select anchor links that start with #
- e.preventDefault(); //prevent normal jump to anchor action
- var elementpos= $($(this).attr('href')).offset().top; //get position of element to scroll to.
- var speed = 400; //time, in milliseconds, for the scroll action to complete.
- $('html, body').animate({scrollTop: elementpos+ 'px'}, speed); //animate the scroll.
- });
- });
What this does :
- Find anchor links and attach a click event to it. (Selectors )
- Obtain element selector to move to using .attr()
- Find the position of the element using .offset()
- 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 .
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.
Artigos semelhantes
- How to make the background image of a button disappear when we click it, and make it appear on another button when we click it in Visual Studio
- Alguém me enviou um link Grabify, mas eu não cliquei no link, isso significa que eles poderiam ter obtido o meu endereço IP?
- O que é o melhor entre os routers: Netgear, TP-Link, D-Link ou ASUS?
- Posso ser hackeado clicando em um link malicioso? O que posso fazer para me proteger se eu clicar em um link malicioso?