Reputation: 149
DOM button is getting clicked with .click()
method, but its not working on document itself.
/* Working fine */
function getAlert() {
alert("Clicked!!!");
}
var btn = document.getElementById('btn');
btn.onclick = getAlert;
btn.click()
/* Should be work */
document.onclick = getAlert;
document.clicked()
<button id="btn">Click Me!</button>
Please help.
Upvotes: 3
Views: 32971
Reputation:
document.getElementById('btn')
this id is not found in the document, So please add the element id and remove document.clicked()
because its not a function on document object.
Here you may please check the working code snippet.
/* Working fine */
function getAlert() {
alert("Clicked!!!");
}
var btn = document.getElementById('btn');
btn.onclick = getAlert;
btn.click()
/* Should be work */
document.onclick = getAlert;
//document.clicked()
<button id="btn">Click Me!</button>
Upvotes: 6
Reputation: 14541
As Quentin already explains in his answer, a document
object cannot be clicked upon.
Event handlers associated on document
execute due to the events bubbling up the DOM. For example, a click event on the button in your snippet traverses the button -> then body -> then document.
So, as an alternative to document.clicked()
you attempt in your question, you can trigger the event on body
element via, document.body.click()
.
/* Working fine */
function getAlert() {
alert("Clicked!!!");
}
var btn = document.getElementById('btn');
btn.onclick = getAlert;
btn.click()
/* Should be work */
document.onclick = getAlert;
document.body.click()
<button id="btn">Click Me!</button>
You can read more about event bubbling here: What is event bubbling and capturing?
Note: I have added ID attribute to the button in your snippet to ensure that it runs.
Upvotes: 1
Reputation: 551
you can do this with jquery like this:
$(document).on('click', ()=>{console.log('clicked')})
$(document).click()
Upvotes: 0
Reputation: 943214
document
objects are not things that can be clicked on.
Event handlers can be bound to a document
, and events will bubble until they reach the document
and trigger a handler, but you can't click directly on the document
.
Upvotes: 7