1

I am having an issue here: I have a URL like so:

products.php?community=2#1855

and I have an element like so:

<div id="1855"></div>

the element with the id 1855 is being created by jquery.

Anyways, when I load this page, the page does not goto that id. is this due to the fact that element is created by jquery? If so, does anyone know of away I can goto that id after it was created?

I tried this:

$("html, body").animate({ scrollTop: $('#1855').offset().top }, 1000);

but got this error:

Uncaught TypeError: Cannot read property 'top' of undefined
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
user979331
  • 11,039
  • 73
  • 223
  • 418

4 Answers4

0

It seems that selector could not find an element. You need to animate scrollTop after adding the new element. Something like this:

$('#listings').html(html);
$("html, body").animate({ scrollTop: $('#1855').offset().top }, 1000);
Tomasz
  • 106
  • 1
  • 7
0

What happens is that the url:

products.php?community=2#1855

It is generated before the jQuery object exists, one way you can prove that it works is to do this:

setTimeout(function(){
    $("html, body").animate({ scrollTop: $('#1855').offset().top }, 1000);
},500);

This will make the jQuery object exists when you run this function.

Note: This example is for you to try.

Joel Jaime
  • 459
  • 2
  • 9
0

If your document is being populated dynamically, I think the best solution would be add some code to check if the element referenced by the anchor was created whenever you add a new element, and scroll to it once it's there.

If this isn't possible, another solution is to hook into the DOM change event and check if the element referred to in the anchor exists. This isn't reliable on old browsers (including IE9), however.

navigatedToAnchor = false;
$(document).on('DOMSubtreeModified', function () {
    var anchorIndex = document.URL.lastIndexOf('#');
    if (!navigatedToAnchor && anchorIndex !== -1) {
        var anchorSelector = document.URL.substring(anchorIndex);
        var anchorElement = $(anchorSelector);
        if (anchorElement.length > 0) {
            $('html, body').animate({ scrollTop: anchorElement.offset().top }, 1000);
            navigatedToAnchor = true;
        }
    }
});
Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
0

it seems that you have a DOM readiness issue.

The first thing to do would be to wrap your line to scroll:

$("html, body").animate({ scrollTop: $('#1855').offset().top }, 1000);

like this:

$(document).ready(function(){
/* dom is ready, scroll here */
$("html, body").animate({ scrollTop: $('#1855').offset().top }, 1000);
})