RasikaSam
RasikaSam

Reputation: 5573

JavaScript Scroll current view's element id

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>

Upvotes: 2

Views: 4390

Answers (2)

RasikaSam
RasikaSam

Reputation: 5573

If anybody interest of a out the box solution, take a look at https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery as well. Works well when you mix it with the Mohamed-Yousef answer.

  • Add jquery reference
  • Add jquery.visible.js reference
$(function(){
 $(window).on('scroll',function(){
  $('a[name^="para"]').each(function(){               
      var visible = $(this).visible( false );
      if(visible){
      console.log($(this).attr('name'));
      return false;
          }       
      });
  }); 
});

Upvotes: 0

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

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
            }
        });
    });
});

Demo

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

Upvotes: 4

Related Questions