Hello, I am implementing a webpage in which I want to scroll to the next item when I click on an item. This works fine when it has a specific sequence, but if I want to change an element in a specific section after selecting the wrong element, this sequence will be corrupted. The following is a snippet of code.
$('.item').on('click', function(e) {
$(this).parent().parent().find('p')
.removeClass('selectedItem');
$(this).find('p')
.addClass('selectedItem');
e.preventDefault();
var $current = $('.first'),
$next = $current.nextAll('.step').first();
if (!$next.length) {
$next = $('.step').first();
}
if ($next.length) {
var $next = $next.first();
var top = $next.offset().top;
$current.removeClass('first');
$('body').stop(true, true).delay(1000).animate({
scrollTop: top
}, 1000, function() {
$next.addClass('first');
});
}
});
.selectedItem {
background-color: red;
}
.step {
background-color: blue;
height: 500px;
}
.item {
border: 2px white solid;
height: 50px;
width: 50px;
margin: 5px;
float: left;
}
p {
margin: 5px;
height: 40px;
width: 40px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="step first">
<h1 class='section'>
First Section
</h1>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
</div>
</div>
<div class="step">
<h1 class='section'>
Second Section
</h1>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
</div>
<div class="step">
<h1 class='section'>
Third Section
</h1>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
<div class="item">
<p>
hello
</p>
</div>
</div>
Run codeHide resultIn the above example, there are three sections and allows you to say that if I click on an element in section 1, then the scroll goes to section 2. The same goes for the element in section 2, but if I manually scroll to the previous section and correct my element, this sequence is confused.