On click anchor and scroll, need to add a class to each first div which is the child element of particular ID.
$(document).ready(function() {
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
$(".box:first").addClass("black");
});
} // End if
});
});
#Segment1 {
background-color: yellow;
padding: 50px;
}
#Segment2 {
background-color: pink;
padding: 50px;
}
.box {
padding: 10px 20px;
border: 1px solid #000000;
margin-bottom: 5px;
}
.gray {
background-color: lightgray;
}
.black {
background-color: black;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<a href="#Segment1" class="">Segment1</a>
<a href="#Segment2" class="">Segment2</a>
<br><br><br><br><br>
<div id="Segment1">
<div class="box gray">Lorem Ipsum...</div>
<div class="box gray">Lorem Ipsum...</div>
<div class="box gray">Lorem Ipsum...</div>
</div>
<div id="Segment2">
<div class="box gray">Lorem Ipsum...</div>
<div class="box gray">Lorem Ipsum...</div>
<div class="box gray">Lorem Ipsum...</div>
</div>
2
Answers
You can use the
hash
variable value to achieve your goal. Also use:eq(index)
to select the first box each time.Working snippet:
Here is my suggestion.