Question

I am using Chris Ferdinandi's Smooth Scroll script and I am trying to have it scroll to an element, but land with that element centred. Similarly to what is done at http://www.spotify.com.

I attempted adding the following code to the start of the script:

$(document).ready(function(){

    $('.downarrow a').click(elementhref = $('.downarrow a').attr('href'));

    var elementheight = $(elementhref).height();
    var windowheight = $(window).height();

    if (elementheight < windowheight) {
        topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
    } else {
        topoffset = 0;
    }

});

I then added the variable topoffset into the script so that it offsets the anchor's position by the correct amount.

var endLocation = _getEndLocation( document.querySelector(anchor), topoffset ); // Scroll to location

It works perfectly for the first section, but when I click on the next .downarrow a element, my code only ever uses the height of first section. But I have several of these links with the same class throughout my HTML.

This is a simplified version of what I have:

<section id="home">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#about">Scroll Down</a></div>
</section>

<section id="about">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#portfolio">Scroll Down</a></div>
</section>

<section id="portfolio">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#contact">Scroll Down</a></div>
</section>

<section id="contact">
  <!--content-->
</section>

I was trying to have it change the elementhref variable depending on which element was clicked, but this would obviously not work with my code. I tried giving each downarrow a unique ID but it became too complicated for me.

This is my first time using JavaScript and jQuery, so I'm hoping there's a simple solution I've overlooked.

Was it helpful?

Solution

Try

(function() {

   function setStuff(elementhref) {

      var elementheight = $(elementhref).height();
      var windowheight = $(window).height();

      if (elementheight < windowheight) {
        topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
      } else {
       topoffset = 0;
      }

   }

   $('.downarrow a').click(function() {
     setStuff( $(this).attr('href') );
   });

})();

Only targeting the one you have 'clicked' - this - and making a jquery object of out it so you can access the jquery methods $(this)


Edit/Update - added in the parts to connect the click handler with a function to dostuff

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top