Stack Overflow Asked by dzwash on December 13, 2021
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>
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.
Answered by Victor on December 13, 2021
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>
Answered by Mr. Polywhirl on December 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP