jQuery smooth scoll breaks with AJAX call

I’ve searched and I’ve searched for what the cause of this problem could be. But every time I search I get “how to add smooth scrolling”. This is NOT the issue. I have a wordpress setup, and smooth scrolling works fine in every instance, except with the result appended from a JS file.

$(document).ready(function(){
function descriptions(){
    var apiCall = '[APIRUL]';

    $.ajax({
        url: apiCall,
        type: 'get',
        dataType : 'json',
        success: function(data){
            $.each(data, function(i, p) {
                var name = p.name;
                var namelc = p.namelc; //lowercase
                var description = p.description;
                var output = '<div id="' + namelc + '"><h3">' + name + '</h3><p>' + description + '<br /><a href="#table">back to top</a></p></div>';

                $('#description').append(output);
            });
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });
}descriptions();
});

Everything returns fine. There is no problem with the jQuery or AJAX itself. But for some reason, the “a href=”#table”” “jumps” back to the table (above the descriptions) and adds the hash the address (e.g. http://example.com/somepage/#anchor) instead of easing to it (like every other anchor link on the same page. I.e. there is nothing wrong with the smooth scroll. Something else is interfering).

Read More

I’m sure there is an explanation and a solution for this behavior. But I just can’t find it because as I mentioned earlier, every time I search for “smooth scroll not working” I end up with tons of “how to add smooth scroll” results.

Any help, in full or a nudge in the right direction, is much appreciated! /stuck!

Related posts

2 comments

  1. If you are using JQuery Smooth scroll from here, it appears that it is handled like a listener. If you inject with AJAX, there will be no listener on that link. Rerun the bind – something like this:

    $('#description a').smoothScroll();
    

    AFTER this line in your code:

    $('#description').append(output);
    
  2. So, thanks to Peter Mark’s answer (thank you for that! Really. I had been stuck on this for over a day. And it would have been longer without your help, thats for sure!) I understood what was going on and that helped solving the problem. For now, without digging thru layers of files to see where the initial smooth scroll comes from (what the listener is called), this is a working solution. Bringing back that nice smooth scroll to all jQuery appended elements 😀

    $('a').click(function(){
        $('html, body').animate({
            scrollTop: $(this.hash).offset().top
        },350,'easeInOutExpo');
        return false;
    });
    

    Like Peter explained, this needs to go in AFTER appending (otherwise we would just be targeting existing anchors, not the new ones we’re creating/injecting with the append).

Comments are closed.