I am trying to manipulate user click. Let say user clicked anywhere on the webpage but image in the DIV will get clicked.
I am trying with co-ordinate :
// Add an event listener to the document to listen for clicks
document.addEventListener('click', function(event) {
// Get the coordinates of the user's click
var x = event.pageX;
var y = event.pageY;
// Calculate the coordinates of the new element based on the user's click
var newX = x + 90; // adjust the value of newX as needed
var newY = y + 150; // adjust the value of newY as needed
// Get the element that you want to click on
var element = document.elementFromPoint(newX, newY);
// Create a new click event
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
// Dispatch the click event on the element
element.dispatchEvent(clickEvent);
});
But this script did not worked. So, i thought maybe due to co-ordinate change based on screensize and viewport. So, i coded like this
// Get a reference to the element you want to click on
var elementToClick = document.getElementById('my-element');
// Get the bounding rectangle of the element you want to click on
var rect = elementToClick.getBoundingClientRect();
// Calculate the coordinates of the point you want to click relative to the top-left corner of the element
var offsetX = 10; // adjust the value of offsetX as needed
var offsetY = 20; // adjust the value of offsetY as needed
var pointX = rect.left + offsetX;
var pointY = rect.top + offsetY;
// Simulate a click on the point using the coordinates relative to the top-left corner of the viewport
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'clientX': pointX,
'clientY': pointY
});
document.dispatchEvent(clickEvent);
<a href="https://www.stackoverflow.com">Test Click </a>
<div id="my-element"> <a href="https://www.example.com"> <img src ="https://place-hold.it/300x300" /> </a>
But it still not working. can you help me how to achieve this or what is the mistake in my code