Home > database >  how to find the id of the element anchored in a link when user click on the link (JavaScript)
how to find the id of the element anchored in a link when user click on the link (JavaScript)

Time:08-21

This is a landing page project. it has 5 html sections. it also has a dynamic navigation bar at the top that links the sections. whenever a section is added in the html it is updated on the navigation bar and links you to the section that you clicked on. I want to use JavaScript to add smooth scrolling behavior whenever I click on the sections (like scrollIntoView()) here is the html of a section

let navList = document.querySelector('#navbar__list'); // stores the <ul>...</ul>
let sectionsNumber = document.querySelectorAll('h2');
const makeNavListItems = () => {
  for (let i = 0; i < sectionsNumber.length; i  ) {
    listItem = document.createElement('li');
    listItem.innerHTML = ` <a   href="#section${i 1}"> Section ${i 1} </a>`;

    navList.appendChild(listItem);
  }
};
<!-- HTML Follows BEM naming conventions
          IDs are only used for sections to connect menu achors to sections -->
<header >
  <nav >
    <!-- Navigation starts as empty UL that will be populated with JS -->
    <ul id="navbar__list"> </ul>
  </nav>
</header>
<main>
  <header >
    <h1>Landing Page </h1>
  </header>

  <section id="section1" data-nav="Section 1" >
    <div >
      <h2>Section 1</h2>
      <p>.....</p>

      <p>.......</p>
    </div>

I must use an event Listener to add this scrolling behavior (project requirement) so i was thinking of something like this

navList.addEventListener('click',function(event){    
 event.preventDefault();
if(event.target.href){document.getElementById().scrollIntoView({behavior:'smooth'})}                                                        })

so this will check if the event target is a link. the problem is I can't find a way to get the id of the element anchored in the link

CodePudding user response:

const navList = document.querySelector('#navbar__list');
const sectionsNumber = document.querySelectorAll('h2');
const makeNavListItems = () => {
    for (let i = 0; i < sectionsNumber.length; i  ) {
        listItem = document.createElement('li');
        listItem.innerHTML = ` <a   href="#section${i 1}"> Section ${i 1} </a>`;
        navList.appendChild(listItem);
    }
};
makeNavListItems();

navList.addEventListener('click', function(event) {
    event.preventDefault();
    if (event.target.href) {
  
  
  
        //here we use uditkumar11's idea to get the id (or rather the query string for getting the element with the id)
        const idQueryStr = event.target.getAttribute('href');
        console.log(idQueryStr);
    
    
    
        const targetElem = document.querySelector(idQueryStr);
        targetElem.scrollIntoView({
            behavior: 'smooth'
        });
    }
});
<body>
    <header >
        <nav >
            <ul id="navbar__list">
            </ul>
        </nav>
    </header>
    <main>
        <header >
            <h1>Landing Page</h1>
        </header>

        <section id="section1" data-nav="Section 1" >
            <div >
                <h2>Section 1</h2>
                <p>.....</p>

                <p>.......</p>
            </div>
        </section>
    </main>
</body>

  • Related