Apologies if this question is already asked/answered. I have an html page (this page has JQuery library) with lots of paragraph tags. Each paragraph (p) tag is associated with an anchor tag with a name. Please note content inside these paragraphs may vary. When user scrolls through the page, how can I get the name of the anchor tag in the current view?
<p><a name="para1"></a> some long text </p>
<p><a name="para2"></a> some text </p>
<p><a name="para3"></a> some long text </p>
you can use
$(document).ready(function(){
$(window).on('scroll',function(){
var Wscroll = $(this).scrollTop();
$('a[name^="para"]').each(function(){
var ThisOffset = $(this).closest('p').offset();
if(Wscroll > ThisOffset.top && Wscroll < ThisOffset.top + $(this).closest('p').outerHeight(true)){
$(this).closest('p').css('background','red');
console.log($(this).attr('id')); // will return undefined if this anchor not has an Id
// to get parent <p> id
console.log($(this).closest('p').attr('id')); // will return the parent <p> id
}
});
});
});
Note: don't forget to include Jquery
To Explain : $(this)
inside .each()
select anchors with name starts with para .. closest('p')
to select parent <p>
of this anchor .. so play around this to reach the thing you want
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments