Ask Your Question
0

How can one use Jquery to click on an anchor link, scroll to a specific accordion or tab, and open it?

asked 2023-02-25 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-11-09 22:00:00 +0000

qstack gravatar image

To achieve this, you can use the following code:

  1. Add a class to the anchor link you want to click on, for example:
<a href="#accordion2" class="scroll-to-accordion">Go to Accordion 2</a>
  1. Add an id attribute to the accordion or tab you want to scroll to, for example:
<div id="accordion2" class="accordion-item">
  <h3 class="accordion-header">Accordion 2</h3>
  <div class="accordion-content">
    <p>Content of accordion 2 goes here</p>
  </div>
</div>
  1. Use jQuery code to handle the click event on the anchor link, scroll to the desired accordion/tabs, and open it:
$(document).ready(function() {
  $('.scroll-to-accordion').click(function(event) {
    event.preventDefault(); //prevent default anchor behavior
    var href = $(this).attr('href'); //get the href attribute value
    $('html, body').animate({
      scrollTop: $(href).offset().top //scroll to the desired accordion/tab
    }, 500, function() {
       $(href + ' .accordion-header').trigger('click'); //click to open the accordion/tab
    });
  });
});

This code will animate the scrolling to the desired accordion/tab and trigger a click event to open it. You can adjust the duration of the scroll animation by changing the value of the second argument of the animate() function.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-25 11:00:00 +0000

Seen: 11 times

Last updated: Nov 09 '22