1

I am trying to make my page autoscroll to a div when a user clicks it. The jQuery I am using only works the first time it's clicked. After that it just produces no result even though it is in the click function. The element offset variable is being calculated correctly, I can see it in the log. However on second click nothing happens Here is my jQuery:

$('.logoWrap').click(function () {

    var body = $("html, body");
    var scrollTop = $(window).scrollTop();
    var elementOffset = $(this).offset().top;
    var distance = (elementOffset - scrollTop);
    body.animate({
        scrollTop: distance
    }, '500', 'swing');)
};

The reason I can't just use and anchor and ID is because when the div is clicked there is another div that slides down to show more content. So I think this is whats messing things up. Here is my code in it's entirety

    $('.logoWrap').click(function(){


            var body = $("html, body");
            var scrollTop     = $(window).scrollTop();
            var elementOffset = $(this).offset().top;
            var distance      = (elementOffset - scrollTop);
            body.animate({scrollTop:elementOffset}, '500', 'swing');


        if($(this).next('article').is(':visible')){

            $(this).parent().animate({marginBottom : 0},'2000');
            $(this).removeClass('activeWork');
            $(this).next('article').slideUp('2000');
        }



        else if($('.logoWrap').hasClass('activeWork')){

            $('.activeWork').next('article').slideUp('2000');
            $('.activeWork').parent().animate({marginBottom : 0},'2000');
            $('.activeWork').removeClass('activeWork');


            var articleHeight = $(this).next('article').height();
            var desiredHeight = articleHeight + 100;

            //open content
            $(this).addClass('activeWork');         
            $(this).next('article').delay('500').slideDown('2000');
            $(this).parent().delay('500').animate({marginBottom : desiredHeight},'2000');   
        }



        else{

        var articleHeight = $(this).next('article').height();
        var desiredHeight = articleHeight + 100;
        //open content
            $(this).addClass('activeWork');         
            $(this).next('article').slideDown('2000');
            $(this).parent().animate({marginBottom : desiredHeight},'2000');                






        }
Ryan Swanson
  • 240
  • 1
  • 5
  • 22
  • 1
    Is there a reason to not just use a link to an element with an id? – Paul Aug 10 '14 at 23:40
  • try `scrollTop: elementOffset` – Umidbek Karimov Aug 10 '14 at 23:43
  • Do all the elements you want to scrollTo already exist inside the DOM or are some loaded dynamically? Does it work the first time for all your div's or just for the first one with the class 'logoWrap'? And add a e.preventDefault() to your click even. Also you should preferably use on('click') – gulty Aug 11 '14 at 13:44

0 Answers0