Home > Software design >  Using a variable to set a ScrollTop with animate function
Using a variable to set a ScrollTop with animate function

Time:12-02

I have a series of divs that collapse and open and I'd like the browser to scroll to the top of the open divs.

I'm trying to do this using anchor links and having the anchor link saved in a variable "scrollClass" but my code is not working. When I test the console log however, it outputs exactly what I want it to output. I'm not sure if this is a syntax situation or not.

I'd appreciate any help that I can get here.

Thanks in advance.

<script>
$('.discover-btn-open, .discover-btn-open a').click(function(e) {
e.preventDefault();
var currentElement = $(document.activeElement);
var scrollClass = $(this).closest('.discover-inner').find('#discover- anchor').attr('href');
$(".discover-inner").removeClass("discover-inner-open");
$(this).closest(".discover-inner").addClass("discover-inner-open");
console.log(scrollClass);
$('html, body').animate({scrollTop: $(scrollClass).offset().top - 100}, 450);
});

$('.discover-close, .discover-close a').click(function(e) {
e.preventDefault();
$(this).closest(".discover-inner").removeClass("discover-inner-open");
});

</script>

CodePudding user response:

You are setting attribute href to scrollClass and when you try to use it as an element it won't work. Try removing the attr("href") part and using the .offset then.

You could also just trigger the click on the anchor element you want to scroll to through jQuery.

  • Related