0

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>
Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278
Robert A
  • 19
  • 2
  • You forgot to post the JS you tried – Roko C. Buljan Nov 04 '19 at 01:09
  • I suggest you at least try before asking in StackOverflow. Here is a similar problem with scrolling to an element (in case you need the animation): https://stackoverflow.com/questions/6677035/jquery-scroll-to-element and then you can just call element.click() – glneto Nov 04 '19 at 01:16
  • I tried that but it did not work for me. – Robert A Nov 04 '19 at 04:01

1 Answers1

2

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>

jsBin live example

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278