Reputation: 7724
Is it possible to scroll to an element with a specific id and a specific class. For example a simple script for smooth scrolling to a specific id is
$(function () {
$('a[href*="#"]').click(function () {
var $target = $(this.hash);
$target = $target.length ? $target : $('html');
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, {duration: 1500, easing: 'easeInOutCubic'});
return false;
});
});
This is useful if you have something like
<div id="space-red"></div>
<div id="space-blue"></div>
<div id="space-green"></div>
However if you have a page such as
<div id="space-red" class="class1"></div>
<div id="space-blue" class="class1"></div>
<div id="space-red" class="class2"></div>
<div id="space-blue" class="class2"></div>
<div id="space-green" class="class1"></div>
Would you be able to navigate between the two space-red
or space-blue
ids by differentiating between the classes they have assigned to them?
Upvotes: 0
Views: 180
Reputation: 86
First, Ids must be unique, but you can use class to control and select element or other attribute. In this way, select the element with the class not flagged, and add a flag on end. Something like:
$(function () {
$('a[href*="#"]').click(function () {
var $target = $(this.hash + ':not(.flag)');
$target = $target.length ? $target : $('html');
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, {duration: 1500, easing: 'easeInOutCubic'});
$('.flag').removeClass('flag');
$target.addClass('flag');
return false;
});});
Upvotes: 0
Reputation: 550
Ids must be unique, try change id
to data-id
, here is an example:
var target = $('div[data-id="space-red"].class2').offset().top;
console.log(target);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="space-red" class="class1"></div>
<div data-id="space-blue" class="class1"></div>
<div data-id="space-red" class="class2"></div>
<div data-id="space-blue" class="class2"></div>
<div data-id="space-green" class="class1"></div>
Upvotes: 1
Reputation: 1
The problem is that you use the classes as if they were IDs and IDs as if they were classes. The IDs are unique for the entire document and therefore should only be one.
You need to think the other way round and logic will correctly.
Upvotes: 0