ScrollTop Not finding one of several different numeric element ids in masonry image thumbnails to scroll page to the image

Viewed 47

I have a set of thumbnails in a masonry layout each of which links to a gallery page. I want to return to the scroll state showing the image which was clicked. I am using the close button on the gallery to add a hash value to the address which I then use to scroll to the image. The code always only selects the first instance of the div to scroll. If I include a clickable link the page scrolls correctly.

html

<div class="item">
  <div id="photo_335"  class="anchor"></div>
    <a href="gallery.php?gallNo=335&catNo=14"><img src="images/gall335.jpg" </a>                                
  </div>                                                                            
  <div class="item">
    <div id="photo_332"  class="anchor"></div>
    <a href="gallery.php?gallNo=332&catNo=14"><img src="images/gall332.jpg"></a>                                                                
  </div>                                        
  <div class="item">
    <div id="photo_323"  class="anchor"></div>
    <a href="gallery.php?gallNo=323&catNo=14"><img src="images/gall323.jpg"></a>
  </div> 

Script

var $hash = window.location.hash;
var $photo = "photo_" +$hash.replace('#', '');
if ($hash.length) {
    $('html, body').stop().animate({
            scrollTop: $($target).offset().top - headerHeight
        }, 10);     
        return false;
 }

site.com/test.php?catNo=14#337
1 Answers

OK solved my problem. I was firing the script before the layout had completed. console.log( $('#'+$photo).offset() ); gave me the position of the div and helped me realise this.

Related