Utilize JavaScript to automatically scroll to the element id of the current view

Is it possible to retrieve the name of an anchor tag in view as a user scrolls through an HTML page with multiple paragraphs and associated anchor tags?

<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>

Answer №1

here is a helpful code snippet for detecting scroll using jQuery:

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

Check out the demo here

Don't forget to include Jquery in your project.

To Explain : $(this) inside .each() selects anchors with name starting with para, while closest('p') selects the parent <p> of this anchor. Feel free to customize this script to fit your needs!

Answer №2

For a unique and innovative solution, explore the possibilities of . This method perfectly complements the Mohamed-Yousef answer.

  • Include jquery reference
  • Include 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;
          }       
      });
  }); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Next.js Configuration Files Explained

Currently, my application is functioning well with the use of Next.js and Next.js API tool for handling requests. The backend is managed through sanity.io which is working smoothly. In my sanity configuration setup, I have a dedicated file named 'san ...

What is the best way to maintain user authentication using Firebase?

After trying a few solutions I found, I am still struggling to persist user authentication with Firebase after a page refresh. It seems like I might be missing some key concepts. I have been following the Firebase documentation and attempted to implement ...

Is there a way to refresh an Angular component in Storybook using observables or subjects?

When I attempt to update my Angular component using a subject in Storybook by calling subject.next(false), I encounter an issue. The instance property of the component updates, but it does not reflect in the canvas panel. Here is my loading component: @Co ...

Determining the position and offset of an element

Currently, I am facing a dilemma with my table of images. I want to add an icon to the corner of each image so that they align perfectly. I attempted to achieve this using relative CSS positioning, but it resulted in the icons extending beyond the cells an ...

Attempting to demonstrate how to handle a duplicate entry error within a MySQL database through the use of Express.js and React.js

I have developed a CRUD application that is functioning perfectly. Now, I am working on adding validation to it in order to notify users when they try to insert an entry that already exists in the database. This is what I have implemented so far: console ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Click to enlarge font size across the entire project

I'm working on a project for elderly users and my client wants a feature where they can easily adjust the font size throughout the application with just one click of a button. What is the best approach for implementing this functionality? My initial ...

Laravel: Issue with displaying stored images from the database

When using Laravel, I encountered an issue where the stored image from the database is not displaying: Even though $post->image has the location posts/1lSBv7Ana8Lonj9Au37IrujjnnEaYgzNWyamch33.jpeg, the image does not show up. The code snippet in index ...

Combining Angular 2 and Symfony 3 for seamless integration

I am currently working on integrating Angular 2 with Symfony 3. After using npm to install node modules, I encountered an issue linking them from my base view base.html.twig. Despite adding scripts, none of them seem to be working or appearing in the page& ...

Is it possible to execute a case-insensitive taffydb query without using the like operator?

When using TAFFYDB, I need to perform a case insensitive query (ignoring upper/lower case). The method "likenocase" seems to combine the functions of "like" and "no case". In essence, if I search for "bm", I want to retrieve BM, bm, Bm, bM. Instead, what I ...

"Unsettled" JavaScript variable persists during Ajax page transition

I'm currently working on a CRUD app using php/js, where an ajax page change is essential. Within the "add view," there is a basic table and a button that adds a new row whenever you click on it. Initially, on the first load, clicking the button adds ...

Unable to retrieve output from jQuery function in PHP

I'm facing an issue retrieving data from the database and I can't seem to pinpoint why there's no output. My approach involves using jQuery/AJAX: $(document).ready(function(){ $('#banktransfer_blz').blur( function(){ ...

What is the best way to incorporate a button in my code that automatically triggers changes at regular intervals?

Is there a way to automatically change the color of my working traffic light in JavaScript on a timed basis, rather than relying solely on button clicks? Here is the current code I am using: <!DOCTYPE html> <html> <head> <style> # ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Discover the methods for accessing an array of IDs by implementing an event trigger in conjunction with checkboxes

Can you assist me with a dilemma I'm facing? I've developed a static form containing numerous checkboxes and checklists. My challenge arises when trying to integrate a JavaScript code that automatically selects subcategories when parent checkboxe ...

Uploading CSV file in Angular to populate the scope rather than sending it to the server

I need assistance with allowing users to upload a CSV file, which will then be displayed and validated. Rather than uploading the file directly to the server, I would prefer to keep it within scope until validation is complete. Unfortunately, Angular 1.5. ...

Traverse the array of nested JSON objects in an iterative manner

I need to iterate through a JSON array object with the following structure: var myJSONObject = { "abc": { "prod_1": [ {"prod_ver" : "prod 1 ver 1"}, {"prod_ver" : "prod 1 ver 2"}, ], "prod_2": [ ...

Do AJAX requests hinder performance and how long do they typically last?

Even though I have experience in web development, I still find myself feeling a bit uneasy asking these basic questions. However, I believe it's always good to verify my assumptions... In my application, I am working on recording unique image views. ...