Recently, I've been working on a small blog and I want to make consecutive blog posts accessible from within an accordion. This will allow users to easily skim through post titles, select the one they find interesting, read it, and seamlessly go back to skimming without having to navigate unnecessary menus.
However, I'm facing an issue where once a user finishes reading a post and clicks on a second one, the second post doesn't open at the top with the title visible. Instead, it opens 2/3 of the way down due to scrolling while reading the first post. This forces the user to manually scroll back up to the top of the post they haven't read yet. I've tried various solutions but nothing seems to work. Any help would be greatly appreciated!
UPDATE: I discovered that the slim version of jQuery I was using didn't have the functions I needed. Now that I've resolved that issue, everything compiles fine but I still can't figure out how to scroll the page to the right position.
The closest solution I found is this code snippet, which scrolls back up to the first card-header
when a new section is opened. However, I want it to scroll to the specific card-header
that was clicked.
$(".card-header").click(function (event) {
$('html, body').animate({
scrollTop: $(".card-header").offset().top
}, 300);
});
I'm attempting to achieve something similar to this logical equivalent piece of code, which unfortunately doesn't scroll at all despite compiling correctly. Even replacing $(this)
with $(event.target)
or $(event.target).parent()
has not yielded any results.
$(".card-header").click(function(event) {
$('html, body').animate({
scrollTop: $(this).offset().top-60
}, 300);
Here's a minimal working example to demonstrate my challenges:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container" id="container">
<div class="card">
<a class="card-header" data-toggle="collapse" href="#sec1">Title1</a>
<div id="sec1" class="collapse" data-parent="#container">
<div class="card-body">
lots and lots of text
</div>
</div>
</div>
<div class="card">
<a class="card-header" data-toggle="collapse" href="#sec2">Title2</a>
<div id="sec2" class="collapse" data-parent="#container">
<div class="card-body">
lots and lots of text
</div>
</div>
</div>
</div>