1. Home
  2. WordPress
  3. [Solved]: Divi Anchor links doesn’t anchor to the correct place

[Solved]: Divi Anchor links doesn’t anchor to the correct place

I recently encountered a problem with anchor links while working on Divi builder for a client project. The issue is, Divi anchor links does not jump to the right section. For example, consider a link http://example.com/#gotohere, upon clicking, the page should scroll  to the section ‘gotohere‘. Well, this works fine if the section (gotohere) and anchor link is on the same page, but does not if it were linked from a different page. Here’s the scenario in my client website.

Home page has different sections like, About us, Services, Gallery, Contact Us etc., Along with home page, there are few other pages too. I needed a common menu for Home page as well as other pages. On other pages (Apart from Home page), the link to ‘About us‘, should still take me to the home page and jump straight to the corresponding ‘About us ‘section.

To achieve this, Divi theme provides a very nice feature whereby you can use element’s ID as anchor links. You can provide CSS ID’s say “aboutus” for any of your Divi Builder components such as section, module etc., then accessing the link: http://example.com/#aboutus would straight away jump to the corresponding component.

However, I found out a problem with this. When accessed the linked from a different page, it would scroll a bit past the top of the target section/module.

After googling around, found a fix:

Navigate to Divi>Theme Options>Integration. Scroll to “Add code to the <head> of your blog“, and add the below JavaScript code.

Divi anchor links fix

<script>
document.addEventListener('DOMContentLoaded', function(event){ 

    if (window.location.hash) {
        // Start at top of page
        window.scrollTo(0, 0);
		
        // Prevent default scroll to anchor by hiding the target element
        var db_hash_elem = document.getElementById(window.location.hash.substring(1));
        window.db_location_hash_style = db_hash_elem.style.display;
        db_hash_elem.style.display = 'none';
		
        // After a short delay, display the element and scroll to it
        jQuery(function($){
            setTimeout(function(){
                $(window.location.hash).css('display', window.db_location_hash_style);
                et_pb_smooth_scroll($(window.location.hash), false, 800);
            }, 700);
        });		
    }
});
</script>

That’s it!

Updated on February 22, 2018

Was this article helpful?

Related Articles

Leave a Comment