Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When URL changes on scroll to a certain hash, add a class to a div

My URL hash changes on scroll from

and so on. It’s a fullpage-scrolling effect.

What I want to do is to add the class .draw-shirt to the div #shirt when the URL changes on scroll to #section–2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this code:

$(document).ready(function () {

        if (window.location.href.indexOf("emotion--2") > -1) {
            $('#shirt').addClass('draw-shirt');
        }
    });
        
        

$(window).scroll(function () {
    
        function locationHashChanged() {
            if(window.location.href.indexOf("emotion--2") > -1) {
                $('#shirt').addClass('draw-shirt');
             }
        }

    });

It’s working, if the URL is www.website.com#section–2 on load but not on scroll.

The code

function isScrolledIntoView(elem) {...etc... 

is not working here because of the fullpage-scrolling-effect.

Thanks for helping.

>Solution :

I think you could use the native hashchange event of the window object.

window.addEventListener('hashchange', function() {
    if (location.hash === '#emotion-2') {
        // your code to add class
   } 
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading