3

I have an accordion with CSS animation that expands the clicked li. This is done using li:target.

Now, I want to scroll to the id that is clicked, but because of the css transition, it ends up being positioned where the li was before the transition was activated.

This is my javascript snippet as of now:

$(document).on('click', '#accordion li', function (e){
    e.preventDefault(); 

      // Call the scroll function
    goToByScroll($(this).attr("id"));
    $('#accordion li').height('');
    $(this).height($('section', $(this)).outerHeight() + $('a', $(this)).outerHeight());
});

// This is a functions that scrolls to #ID

function goToByScroll(id){
    // Scroll
    // Wait until CSS transition is done

    $("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ 
        $('html,body').animate({
            scrollTop: $("#"+id).offset().top},
            'fast');
        $("#"+id).unbind();
    });  
}   

Edit2: After Piotr's suggestion, unbinding the event fixed the buggy behaviour I was having :)

2 Answers 2

2

You can try:

$("#"+id).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(event){ 
    $('html,body').animate({
    scrollTop: $("#"+id).offset().top},
    'fast'
    );
    $(this).unbind(event);
});

Edit: Added the unbind instruction.

Sign up to request clarification or add additional context in comments.

6 Comments

in older IE versions the event doesn't exist
This is actually exactly what I've tried. It seems to work, but when I click a li element that has a lot of content in it, it seems as though the browser brings me to the bottom of the li element. And then scrolls up again. And sometimes it doesn't even hit the correct ID either.
I've updated the code in the first post now. As well as a link to the dev site. I'm also setting the height of the element using javascript as well. Maybe that affects the behavior somehow?
Did you try unbind event after it is called?
I have not. And yes that did make a difference! :) I should have known it was something like that. :) I set this as the answer, allthough I'd appreciate if you edited your post to add the unbinding :) If anyone else is having the same problem :)
|
-1

it's hard to know when the transition ends. You could asume 1000ms eg.

window.setTimeout(function () {
   // your scrolling
}, 1000);

1 Comment

Not recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.