Programmatically click on a non-button element using javascript? - javascript

How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?

Believe it or not, for a fairly basic click, you can just call click on it (but more below): Live Example | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Artificial Click</title>
</head>
<body>
<div id="foo">xxxxxxx</div>
<script>
(function() {
var foo = document.getElementById("foo");
foo.addEventListener("click", function() {
display("Clicked");
}, false);
setTimeout(function() {
display("Artificial click:");
foo.click(); // <==================== The artificial click
}, 500);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
You can also create the relevant type of Event object and use dispatchEvent to send it to the element:
var e = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true
});
foo.dispatchEvent(e);
This gives you the opportunity to do things like set other information (the typical pageX and pageY, for instance) on the event you're simulating.
More about the various event object types in Section 5 of the DOM Events spec.

You can use HTMLElementObject.click()
Something like document.getElementById('div1').click()
See more

Or in jQuery (documentation) to click on a non-button element
$( "#nonButton" ).click();
or to listen for a click on that non-button element
$("#nonButton").on("click", doSomething);

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.getElementById("nonButton").dispatchEvent(evt);
see: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent

document.querySelectorAll('#front-chat-container div[role]')[0].click()
worked for me - to click a div element.

Related

javascript to auto click a link not working

hello im trying to get a script to run so that a link auto clicks after certain amount of time
on familyoffices.com the link is the "we are online" graphic at the bottom right
im using
<script type="text/javascript">
$(document).ready(function() {
setTimeout(function() {
$('#desginstudio-button-image-desktop').click();
}, 300);
});
</script>
unfortunately this isn't firing off....anyone know how i can achieve this?
Try using
<head>
<script>
function haveclicked(){
document.getElementById('myLink').click();
}
</head>
<body onload="setTimeout('haveclicked();',3000);">
<a id="myLink" href="http://www.google.com" target="_blank">GOOGLE</a>
</body>
Consider this from the MDN.. You need to create an event to do this correctly.
function simulateClick() {
var evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
});
var cb = document.getElementById("checkbox"); //element to click on
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
document.getElementById("button").addEventListener('click', simulateClick);
<p><label><input type="checkbox" id="checkbox"> Checked</label>
<p><button id="button">Click me</button>
Instead of
$('#desginstudio-button-image-desktop').click();
Try using
$('#desginstudio-button-image-desktop').trigger('click');
You can try to first locate the iframe and the element in it --
var frame = document.getElementById(/* your frame id*/),
button = frame.contentDocument.getElementById(/* your button id*/);
Then dispatch a synthetic event --
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
Some browsers/versions don't support using click() to trigger a click event. Try using .trigger('click') instead

How to add Accept/Reject All Suggestions to a Google Doc Add-On

I'm creating a GSuite Add-on with various menu items and want users to be able to accept/reject all suggestions in their current Doc.
The client-side javascript code to do this can be found here: https://blog.crozdesk.com/accept-all-changes-in-google-docs-with-one-click/
I've tried to incorporate this into my Add-On in the form of a prompt with two buttons. Here's the Apps Script code:
function suggestions() {
var suggestions = [HTML as per below]
var htmlOutput = HtmlService.createHtmlOutput(suggestions)
.setWidth(300)
.setHeight(100);
ui.showModalDialog(htmlOutput, 'Accept/Reject All Suggestions');
}
Here's the html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form>
<div class="block" id="button-bar">
<button class="blue" id="accept-all">Accept All Suggestions</button>
</div>
<div class="block" id="button-bar">
<button class="blue" id="reject-all">Reject All Suggestions</button>
</div>
</form>
<script>
document.getElementById("accept-all").onclick = accept-all();
document.getElementById("reject-all").onclick = reject-all();
function accept-all() {
google.script.host.close();
//below code from https://blog.crozdesk.com/accept-all-changes-in-google-docs-with-one-click/
var d=document.getElementsByClassName("docos-accept-suggestion");
d = Array.prototype.slice.call(d);
d.forEach(function(n){
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, false);
n.dispatchEvent(e,true);
e = document.createEvent("MouseEvents");
e.initEvent("mousedown", true, false);
n.dispatchEvent(e,true);
e = document.createEvent("MouseEvents");
e.initEvent("mouseup", true, false);
n.dispatchEvent(e,true);
});
}
function reject-all() {
google.script.host.close();
//below code from https://blog.crozdesk.com/accept-all-changes-in-google-docs-with-one-click/
var d=document.getElementsByClassName("docos-reject-suggestion");
d = Array.prototype.slice.call(d);
d.forEach(function(n){
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, false);
n.dispatchEvent(e,true);
e = document.createEvent("MouseEvents");
e.initEvent("mousedown", true, false);
n.dispatchEvent(e,true);
e = document.createEvent("MouseEvents");
e.initEvent("mouseup", true, false);
n.dispatchEvent(e,true);
});
}
</script>
</body>
</html>
The html is presented correctly within the prompt, but when I press either the "Accept All Suggestions" or "Reject All Suggestions" buttons a new tab is opened in the browser pointing to: https://[many-alphanumerics]-script.googleusercontent.com/userCodeAppPanel? with a blank page. The prompt doesn't close, despite "google.script.host.close();" being within both functions.
Is this possible or am I fighting a losing battle? Grateful for any pointers. If there's a simpler way to do this without the prompt (e.g. within the Apps Script function itself), also happy to hear suggestions on that.
Thanks very much!
Have you tried removing the 'form' element? You don't really need it as there's no user input. Because your buttons are wrapped in a <form> tag, clicking on them also raises the 'submit' event of the form that redirects to the URL specified in the <form> 'action' attribute. Usually setting the 'action' attribute equal to "" will redirect to the page itself, but this doesn't seem to work in GAS.
Apparently, GAS-generated forms have default 'action' attribute that you can't override like this.
You could also wrap each button in its own <form> tag and then prevent redirect after submitting the form like this
window.onload = function(){
var form = document.getElementById('form1');
form1.addEventListener('submit', function(event){
event.preventDefault();
//call the function for this form
});
}
You won't need 'onclick' handlers for buttons in this case.

How to trigger MouseDown via PhantomJS?

I tried:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent("mousedown", true, true);
jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0].dispatchEvent(clickEvent);
but it just fails to trigger the action on the site.
no error returned.
This is how you programmatically trigger a click on a DOM element with a "mousedown" event. To answer your question, you need to have two things in your source code:
event listeners to detect the clicks
and
commas between your multiple selectors in your jQuery line.
Please run the snippet below, which shows the modified jQuery line and the listeners running correctly.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// You must have event listeners to see if anything is actually happening. For example, here I will add only a listener to the first element:
jQuery(".left-rail-facets")[0].addEventListener('mousedown', function(e) {
jQuery(".left-rail-facets")[0].innerHTML = "I have received a click.";
}, false);
// Now here is the code from your question. Please see how I have commas instead of spaces in my jQuery selector:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('mousedown', true, true);
jQuery('.left-rail-facets,.facet-list,.facet.CS,.suggestion[data-value="B"],a')[0].dispatchEvent(clickEvent);
});
</script>
</head>
<body>
<h1>I am a Webpage</h1>
<p class="left-rail-facets">I have not received a click.</p>
<p class="facet-list">I have not received a click.</p>
<facet class="CS">I have not received a click.</facet>
<p class="suggestion" data-value="B">I have not received a click.</p>
I have not received a click.
</body>
</html>
You will need to use the document.createEvent and event.initMouseEvent:
var element = document.querySelector('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a');
//or var element = jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0];
var elementRect = element.getBoundingClientRect();
var mouseEvent = document.createEvent('MouseEvents');
mouseEvent.initMouseEvent('mousedown', true, true, window, 0, elementRect.left, elementRect.top);

mousemove handler not called with JQuery .mousemove() or .trigger

when mousemove handler is added with addEventListener(), the handler will never be called
with JQuery simulated event by $(xx).mousemove() or $(xx).trigger(e) where e is a jquery event.
But the listener can be called when the event is simulated with pure JS dispatchEvent.
Anybody can explain? My enviroment is Mac + chrome.
code is here http://jsfiddle.net/eepaul/r8W2h/
<body>
<ul id="id_ul">
<li id="a">oooo</li>
<li id="b">jjjj</li>
</ul>
<p id="console"></p>
</body>
js
var liA = $("li#a")[0];
var ul = $("ul")[0];
var p = $("p#console")[0];
ul.addEventListener("mousemove", function(e) {
$(p).text($(p).text() + "mousemove triggered\n");
}, false);
var event = $.Event("mousemove", {
canBubble:true,
cancelable: true,
view:liA.ownerDocument.defaultView,
detail: 1,
screenX:0, //The coordinates within the entire page
screenY: 0,
clientX: 0, //The coordinates within the viewport
clientY: 0,
ctrlKey:false,
altKey:false,
shiftKey: false,
metaKey:false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
button: 0, //0 = left, 1 = middle, 2 = right
relatedTarget:null
});
//neither of the following 2 ways can trigger the handler
window.setTimeout(function() {
$(liA).trigger(event);}, 1000);
window.setTimeout(function() {
$(liA).mousemove();}, 1000);
Hmm. seems a known issue in jquery.
http://bugs.jquery.com/ticket/4314

Javascript: click() not navigating to the link in Firefox 2

While following the answer here: Click() works in IE but not Firefox
I no longer get the "click is not a function message" error message and indeed get the "Clicked" alert message, however the browser does not navigate to the page. I tried it on the latest version of firefox and it navigates, just not happening in Firefox 2.
HTMLElement.prototype.click = function() {var evt =
this.ownerDocument.createEvent('MouseEvents');evt.initMouseEvent('click', true, true,
this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0,
null);this.dispatchEvent(evt);};
document.onclick= function(event) { if (event===undefined) event= window.event; var target=
'target' in event? event.target : event.srcElement; alert("clicked");};
document.getElementById("anId").click();
document.onclick= function(event) { if (event===undefined) event= window.event; var target=
'target' in event? event.target : event.srcElement; alert("clicked");};
Use document.getElementById("anId").onclick(); it will work on all the browsers. click(); works only on IE.
I think since FF2 is too old and not sure whether it supports the click prototype, better way would be to something like this
html
<a id="link" href="url">click here</a>
js
$(document).ready(function(){
$("#link").click(function(){
window.location.href = $(this).attr('href');
});
});
also if this is somethng you don't want to do theb also try something like this:
$(document).ready(function(){
$("#link")[0].click();
});
You may try jQuery plugin and use it's .click() event.
You can see more details here.
Hope this helps.. :)
This question has already been answered here.
Here's what you're to use to add the functionality...
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
Try to use JQuery...
http://api.jquery.com/click/
maybe you are trying to listen on an html element that does not expect to accept onClick event. click() only works in IE. and if you gonna try Jquery event listener click, you can cover all the problems in all major browsers

Categories