Reputation: 19
Need to write a JS or jQuery that when the first button is clicked it scrolls down to an <a>
tag and then clicks that <a>
tag. Any help greatly appreciated. HTML below:
<a href="" id="reserveButton">Reserve Now</a>
<div class="spacerDiv"></div>
<a id='secondClick' href="http://www.google.ca" target="_blank">Click here again</a>
Upvotes: 0
Views: 149
Reputation: 206078
Use href="#secondClick"
to automatically scroll the page, than simply perform a click()
on the desired Element:
const EL = sel => document.querySelector(sel);
EL("#reserveButton").addEventListener('click', () => {
// Page is already scrolled at this point since we used #hash href
// So just perform a click...
EL("#secondClick").click();
});
<a href="#secondClick" id="reserveButton">Reserve Now</a>
<div class="spacerDiv" style="height: 200vh;">some space... scroll down</div>
<a id='secondClick' href="https://www.google.ca" target="_blank">Click here again</a>
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
If you want to use a better UX (animation) you could use JS's Element.scrollIntoView()
const EL = sel => document.querySelector(sel);
const el_reserve = EL("#reserveButton");
const el_second = EL("#secondClick");
el_reserve.addEventListener('click', (evt) => {
evt.preventDefault(); // Prevent default browser action
el_second.scrollIntoView({behavior: "smooth"});
el_reserve.__is_clicked = true;
});
new IntersectionObserver((entries, obs) => {
if (el_reserve.__is_clicked && entries[0].isIntersecting) {
el_second.click(); // Perform a click when element is in viewport
el_reserve.__is_clicked = false; // reset
}
}).observe(el_second);
<a href="#secondClick" id="reserveButton">Reserve Now</a>
<div class="spacerDiv" style="height: 200vh;">some space... scroll down</div>
<a id='secondClick' href="https://www.google.ca" target="_blank">Click here again</a>
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
Upvotes: 1