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);
Related
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
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.
I expect my CustomEvent to be propagated from document to all the DOM elements.
For some reason, it does not happen. What am I doing wrong?
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
By default Custom Events are not bubbled.
Reason being, Custom Event definition says:
let event = new CustomEvent(type,[,options]).
Options have a flag : bubbles, which is false by default, we have to enable it.
Following will fix your code
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchEvent(new CustomEvent("myEvent",{detail:null,bubbles:true}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
You have to dispatchEvent the event on the element you want the event 'triggered' on. It will then propagate down and back up the DOM
<html>
<script>
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
myDiv.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
fiddle: https://jsfiddle.net/yrf9cvr3/
How propagation works: The event starts at the document and works it's way down to the element it was dispatched on (You can capture the event going this way using onCapture flag). Then goes back up to the document. Because you are dispatching on the document the event doesn't really go anywhere, only document see the event.
This is currently not possible as stated in the MDN doc https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#event_bubbling, event can only bubble from child to ancestors, i.e. upward for now.
The best way you can achieve this is use document.querySelector to target the element(s) you want to dispatch the event to, then dispatch as needed.
document.querySelector("#myDiv").dispatchEvent(customEv);
Try this one. Use document.querySelector and specify the events you want to track. Click the button or type some text in the text box
<html>
<script>
function onLoad() {
// var myDiv = document.getElementById("myDiv");
// myDiv.addEventListener("myEvent",function(){alert("Yes!");});
// document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
var myDiv = document.querySelector("#myDiv");
myDiv.addEventListener("click", myEventHandler, false);
myDiv.addEventListener("change", myEventHandler, false);
}
function myEventHandler(e)
{
alert('Element was '+e.target.id+'\nEvent was '+e.type);
}
</script>
<body onload="onLoad()">
<div id="myDiv">
<input type="button" id= "Button 1" value="Button 1"><br>
<input type="text" id="Text 2">
</div>
</body>
</html>
I am posting some solution, not really an answer.
This will propagate a custom event to all the elements in the DOM.
<html>
<script>
document.dispatchCustomEvent = function(event) {
function visit(elem,event) {
elem.dispatchEvent(event);
var child = elem.firstChild;
while(child) {
if(child.nodeType==1) visit(child,event);
child = child.nextSibling;
}
}
visit(document.documentElement,event);
}
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent",function(){alert("Yes!");});
document.dispatchCustomEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>
Going with the extreme. Events propagate down to the element they are dispatched on and back up... So in order to trigger an event on any and essentially all elements (since it is unknown which elements need the event) you can find the "ends" of all of the "branches" of the DOM and dispatch events to them.
jQuery makes it easy to select the end of the branches
function onLoad() {
var myDiv = document.getElementById("myDiv");
myDiv.addEventListener("myEvent", function() {
alert("Yes!");
});
$(':not(:has(*))').each(function(i, el){
el.dispatchEvent(new CustomEvent("myEvent", {
detail: null,
bubbles: true
}));
});
}
https://jsfiddle.net/dkqagnph/1/
Using this will ensure EVERY DOM element (attached to the body) gets the event (assuming that no element stop propagation itself) and thus making there be no need to know which elements are listening or care about the event. This doesn't dispatch to every individual element, as that would be overkill, but just the end and lets bubbling do it's thing.
NOTE: elements with more than one child will get the event more than one time. You may want to have a way to ensure that your code does run more than once or does not care if it runs more than once.
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.
here is my code
<html>
<head>
<script type="text/javascript">
window.onload = function(){
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>
</body>
</html>
"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.
Bind the event to a parent element, that already exists in the DOM:
document.body.addEventListener('click', function (e) {
if (e.target.tagName.toLowerCase() == 'select') {
alert('You clicked a select!');
}
});
JS Fiddle demo.
It would be slightly more sensible to bind the click to an element 'closer' to the form, and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.
jQuery's live function works by using "Event Delegation". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that (with the exception of some) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.
Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.
<html>
<head>
<script type="text/javascript">
window.onload = function(){
// get the relevant container
var eventContainer = document.getElementById("EventContainer");
// bind a click listener to that container
eventContainer.onclick = function(e){
// get the event
e = e || window.event;
// get the target
var target = e.target || e.srcElement;
// should we listen to the click on this element?
if(target.getAttribute("rel") == 'click-listen')
{
alert("You clicked something you are listening to!");
}// if
};
};
</script>
</head>
<body>
<div id="EventContainer">
<input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
<input type="button" name="anotherButton" value="Not listening." />
<p>I'm also listening to this a element: listening to this</p>
</div>
</body>
</html>
there's no need to bind the onclick handler to every select every time you add one.
I am not going to retype your whole page, but you'll see what's going on by reading following snippets:
function handler() {
alert('You clicked a select!');
}
window.onload = function(){
sel = document.getElementsByTagName('select');
for(int i= 0; i < sel.length; i++) {
sel[i].onclick = handler;
}
}
function addSelect() {
var slt = document.createElement("select");
document.getElementById('ss').appendChild(slt);
slt.onclick = handler;
}
<input type="button" onclick="addSelect();"/>
You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.
here's the dumb way to do it:
<html>
<head>
<script type="text/javascript">
function update () {
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
window.onload = update;
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>
</body>
</html>
You can use a cross-browser solution as shown below to add event handler dynamically
sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
if (sel[i].addEventListener){
sel[i].addEventListener("click", clickHandler, false);
} else if (sel[i].attachEvent){
sel[i].attachEvent("onclick", clickHandler);
}else{
sel[i].onclick = clickHandler;
}
}
function clickHandler(event){
}