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

3 Answers 3

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.