1

I am new to JS. I am trying to write function on onclick event listener to get the # value and to pass the value to another function. Can you please help me. When user try to click the a tag i want to capture the # value and to pass the href value to the below function for scroll top offset

<ul class="scrolltop scrolltop">
  <li>
    <a href="#Covered">What’s covered</a>
  </li>
  <li>
    <a href="#Collect">Personal Information</a>
  </li>
</ul>
var tabScroll = document.querySelector("#Collect")
window.scrollTo({
  'behavior': 'smooth',
  'left': 0,
  'top': tabScroll.offsetTop - 110
});
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Does this answer your question? [Smooth scrolling when clicking an anchor link](https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link) – kmoser Aug 12 '20 at 03:27

3 Answers3

1

For event listeners I recommend jquery; it should look something like this.

$(document).on('click', 'a', function() {
    href_val = $(this).attr('href');
    myFunction(href_val);
});
Adam Manji
  • 36
  • 1
1

A solution written in pure Javascript:

document.querySelectorAll('a').forEach(function(element) { // Get all a elements and perform action on them
  element.addEventListener('click', function() {
    // Do something
  })
})
<ul class="scrolltop scrolltop">
  <li>
    <a href="#Covered">What’s covered</a>
  </li>
  <li>
    <a href="#Collect">Personal Information</a>
  </li>
</ul>
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
1

if you need to get the href value in every , you can do something like:

const tabScroll = document.getElementsByTagName("a")

// Here you add the events:
[...tabScroll].forEach(link => link.addEventListener("click", getLinkValue));

// Here you pass the scroll element to the scrollTo function
function getLinkValue(event){
  const linkElement = event.target;
  const hrefValue = linkElement.href.split("#")[1];  
  const hrefWithHash = `#${hrefValue}`
  
  window.scrollTo({
  'behavior': 'smooth',
  'left': 0,
  'top': linkElement.offsetTop - 110
});

}
<ul class="scrolltop scrolltop">
  <li>
    <a href="#Covered">What’s covered</a>
  </li>
  <li>
    <a href="#Collect">Personal Information</a>
  </li>
</ul>
Oscar Velandia
  • 1,157
  • 1
  • 7
  • 9