Is there a way I could refactor the below code so it doesn’t matter how many elements with ID there is? This is what I’ve got so far.
$(window).scroll(function(){;
top = Math.floor( $(window).scrollTop() );
if(top<=$('#div-1').offset().top) {
var value = $('#div-1').attr('data-value');
console.log(value);
} else if(top<=$('#div-2').offset().top) {
var value = $('#div-2').attr('data-value');
console.log(value);
} else if(top<=$('#div-3').offset().top) {
var value = $('#div-3').attr('data-value');
console.log(value);
} else if(top<=$('#div-4').offset().top) {
var value = $('#div-4').attr('data-value');
console.log(value);
}
});
4
Answers
I think you can do
I didn’t check if your code works nor didn’t try to improve it. Just refactored it to be the same as your functionality.
To achieve this you could put the same
class
on all thediv
elements. Then you can use a loop in your jQuery logic to determine which are below the current scroll position.Also note the use of
data()
in the following example to retrieve thedata-*
attribute instead ofattr()
You can create a common class and keep iterating until you find what meets your condition and then attribute it.
If the page is not dynamically generated.
I haven’t run the code specifically, there may be a problem