dzwash
dzwash

Reputation: 1

How to trigger button with html href?

I have the following code in my HTML/CSS/Div table, and the href works without issue. Is it possible to replace the href code such that when this image is clicked, instead of opening the URL, a button click is activated?

Working Code

<a class="test-link" href="https://www.example.com" target="_blank" rel="noopener">
  <img class="testgrey" src="./grey.svg" />
  <img class="test-white" src="./white.svg" />
</a>

Desired Outcome from clicking on the image defined above:
this button gets activated without actually placing the button on the html page:

<a class="button button--small card-figcaption-button quickview" tabindex="0" data-product-id="113">Buy</a>

Upvotes: 0

Views: 1216

Answers (2)

Victor
Victor

Reputation: 124

You can attach an event listener directly to the <a> element and call the button handler;

document.querySelector('.test-link').addEventListener('click', function(event){
   //prevent navigation
   event.preventDefault();
   event.stopPropagation();

   // call your button handler directly
   callButtonEventHandler();

   return false;
});

You can't trigger a button click without a button on the page. You can only call it's handler if it's available in javascript.

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48683

You can add a click handler to your anchor that delegates a click event to the button.

// Delagate the link click to the button click
document.querySelector('#my-link').addEventListener('click', e =>
  document.querySelector('#my-button').click());

// Handle button clicks
document.querySelector('#my-button').addEventListener('click', e =>
  console.log('button click...'));
<a id="my-link" href="#">Click Me</a><br><br>
<button id="my-button">I will be clicked programatically</button>

Upvotes: 1

Related Questions