How do I programmatically click on an element in JavaScript? - javascript

In IE, I can just call element.click() from JavaScript - how do I accomplish the same task in Firefox? Ideally I'd like to have some JavaScript that would work equally well cross-browser, but if necessary I'll have different per-browser JavaScript for this.

The document.createEvent documentation says that "The createEvent method is deprecated. Use event constructors instead."
So you should use this method instead:
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
and fire it on an element like this:
element.dispatchEvent(clickEvent);
as shown here.

For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...
var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);
while (element)
{
if (element.tagName == "A" && element.href != "")
{
if (element.target == "_blank") { window.open(element.href, element.target); }
else { document.location = element.href; }
element = null;
}
else
{
element = element.parentElement;
}
}

Using jQuery you can do exactly the same thing, for example:
$("a").click();
Which will "click" all anchors on the page.

element.click() is a standard method outlined by the W3C DOM specification. Mozilla's Gecko/Firefox follows the standard and only allows this method to be called on INPUT elements.

Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:
var link = document.getElementById(linkId);
link.onclick.call(link);

Here's a cross browser working function (usable for other than click handlers too):
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}

I used KooiInc's function listed above but I had to use two different input types one 'button' for IE and one 'submit' for FireFox. I am not exactly sure why but it works.
// HTML
<input type="button" id="btnEmailHidden" style="display:none" />
<input type="submit" id="btnEmailHidden2" style="display:none" />
// in JavaScript
var hiddenBtn = document.getElementById("btnEmailHidden");
if (hiddenBtn.fireEvent) {
hiddenBtn.fireEvent('onclick');
hiddenBtn[eType]();
}
else {
// dispatch for firefox + others
var evObj = document.createEvent('MouseEvent');
evObj.initEvent(eType, true, true);
var hiddenBtn2 = document.getElementById("btnEmailHidden2");
hiddenBtn2.dispatchEvent(evObj);
}
I have search and tried many suggestions but this is what ended up working. If I had some more time I would have liked to investigate why submit works with FF and button with IE but that would be a luxury right now so on to the next problem.

Related

disable webapp scrolling without killing click (tap) events in javascript

This is my first post so ill try to explain it clear:
Im working on a web application, but the main point is, that i want let my users feel like its a native app. In a native app you cant scroll like in iOS safari so i tried to disable scrolling with event.preventDefault. This works great except that form elements and links arent tapable anymore. My solution to that was this little script, but if you start a touch on one of the escaped elements, it scrolls anyway. Not a big deal but its driving me insane...
notes to script:
isTouch returns true/false if its a touchable device
the .contains method returns true/false if an array contains a string
if (isTouch) {
window.addEventListener("touchstart", function (evt) {
var target = evt.touches[0].target;
var tags = 'a input textarea button'.split(' ');
if ( tags.contains(target.tagName) === false ) {
evt.preventDefault();
}
}, false);
}
EDIT
My main question is, is there a solution to fire the tap event without a touchmove event to allow scrolling
EDIT 2
I solved the problem. My solution is, to emulate the events on interactive elements:
var eventFire = function (el, etype) {
if (el.fireEvent) {
(el.fireEvent('on' + etype));
}
else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
if (isTouch) {
window.addEventListener("touchstart", function (evt) {
var target = evt.touches[0].target;
var foc = 'input textarea'.split(' ');
var clck = 'a button'.split(' ');
if ( foc.contains(target.tagName) ) {
target.focus();
eventFire(target,'click');
evt.preventDefault();
}
else {
evt.preventDefault();
}
}, false);
}

Fire event in Raphael.js

I have an Raphael element with click event handler:
var paper = Raphael("container", 770, 160);
var c = paper.rect(10, 10, 50, 50);
c.click(function () {
alert("triggering");
})
How I can manually fire this event? (c.click() don't work)
Thanks!
Although this question is already answered, I will post my solution which I found out by random.
It's possible with the Raphael internals:
When you attach an event listener like element.click(func) then the element object holds an array with all events. In this array there's an object which has a method f (strange naming convention) which triggers the event.
So to sum it up you can call your event with knowing the order of your events, in your case there's just the click event which is on index 0, you can call it like: c.events[0].f();
A more generic solution would be a function like
function triggerClick(element) {
for(var i = 0, len = element.events.length; i < len; i++) {
if (element.events[i].name == 'click') {
element.events[i].f();
}
}
}​
But beware that if you had multiple click events all were triggered.
Here's a fiddle to demonstrate.
Even though this has already been answered a while ago, I was looking for something a little "more native" in nature. Here's how I go about it without relying on Mootools or jQuery.
var evObj = document.createEvent('MouseEvents');
evObj.initEvent('click', true, false);
c.node.dispatchEvent(evObj);
This basically creates the event in the browser and then dispatches it to the node associated with the Raphaël object.
Here's also the MOZ link for reference:
https://developer.mozilla.org/en-US/docs/DOM/document.createEvent
I actually found a slightly more elegant way to use Kris' method.
Raphael supports native extension of the element object so I built a little patch to add the trigger method to raphael
here it is:
//raphael programatic event firing
Raphael.el.trigger = function (str, scope, params){ //takes the name of the event to fire and the scope to fire it with
scope = scope || this;
for(var i = 0; i < this.events.length; i++){
if(this.events[i].name === str){
this.events[i].f.call(scope, params);
}
}
};
I set up a Js fiddle to show how it works: here
EDIT :
The solution purposed by Dan Lee is working better.
I write a plug-in for this, use event to calculate the right position;
Raphael.el.trigger = function(evtName, event) {
var el = this[0]; //get pure elements;
if (event.initMouseEvent) { // all browsers except IE before version 9
var mousedownEvent = document.createEvent ("MouseEvent");
mousedownEvent.initMouseEvent (
"mousedown", true, true, window, 0,
event.screenX, event.screenY, event.clientX, event.clientY,
event.ctrlKey, event.altKey, event.shiftKey, event.metaKey,
0, null);
el.dispatchEvent (mousedownEvent);
} else {
if (document.createEventObject) { // IE before version 9
var mousedownEvent = document.createEventObject (window.event);
mousedownEvent.button = 1; // left button is down
el.fireEvent (evtName, mousedownEvent);
}
}
};
Usage:
circle2.mousedown(function(e) {
var circle = this.clone();
circle.drag(move, down, up);
circle.trigger("mousedown", e);
});

only writing "return false" once to handle clicking on many links

Instead of writing return false; many times is there a way to set a collection of links such that if any of them are clicked the click function would return false;? I'd still like to have most links return true so showing code that would return true vs. return false would be particularly appreciated.
The goal is writing less code. I'd also like to know if this is a bad idea for reason I can't understand.
The simpliest method is binding one event listener to the document, and checking for the target: http://jsfiddle.net/gKZ7q/
document.addEventListener('click', function(e) {
if (e.target.nodeName.toUpperCase() === 'A') e.preventDefault();
}, false);
For anchors with nested elements, you have to add an additional loop:
var targ = e.target;
do {
if (targ.nodeName.toUpperCase() === 'A') {
e.preventDefault();
break;
}
} while ((targ = targ.parentNode) !== document.documentElement);
// document.body should be fine. Using document.documentElement in case
// that a fool places an anchor outside the <body>
Links can also be triggered through a key event.

The Problem of Selecting Unread Messages in Gmail with JQuery

In Gmail, clicking on the checkbox shown below selects all messages and I'm making a userscript (for personal use and I need it to work in Chrome) that'll select the unread messages only (only the first 2 messages in the screenie below are unread) instead of the default behavior of that checkbox.
My first idea is to simulate click events and although I could access the "unread" menuitem fine using the code...
var unread_menuitem = document.getElementById('canvas_frame').contentWindow.document.getElementById(':s2');
$(unread_menuitem).css({'border':'thin red solid'});
and dispatch the click event to it using the code...
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent( 'click', true, true );
unread_menuitem.dispatchEvent(clickEvent); // Chrome's console returned 'true'
the unread messages don't get selected.
My second idea was to brute force the selection by checking the checkbox $('#canvas_frame').contents().find('tr.zE input').prop('checked', true) and apply the css styles that Gmail applies on a manual click event, but while I was able to match the manual click event both visually as well as DOM-wise (afaik)...
Gmail says "No conversations selected" while performing some action, in this case I did a "Mark as Read". I also want to note that manually clicking on the checkboxes that were put in this state using my brute force method did not "uncheck" them as you'd expect. They needed one additional manual click to get unchecked.
Both my ideas have bombed and I want to know if there are others ways to tackle this, or if there are ways to improve upon my ideas above that can solve the problem.
There's a script here that looks it does what you're trying to do. Is that the whole script you needed to create or was that just part of the functionality?
According to the discussions, they did create it for Firefox which it works in, some people have commented it doesn't work in Chrome, so you might be looking at a solution that needs to target different browsers (your question doesn't specify if it must work in Chrome, just that you were using it).
This is what they are using to select the unread messages, it looks like they are simulating the mousedown and mouseup events on each item:
var handler = function(type,e) {
e.preventDefault();
e.stopPropagation();
var e2 = document.createEvent('MouseEvents');
e2.initEvent('mousedown',true,false);
var el = anchor.wrappedJSObject;
el.dispatchEvent(e2);
setTimeout(function() {
var el = document.querySelectorAll('div[selector='+type+'] > div')[0].wrappedJSObject;
var e2 = document.createEvent('MouseEvents');
e2.initEvent('mouseup',true,false);
el.dispatchEvent(e2);
},100);
}
They are calling this by setting up a click event further down which calls handler('unread',e);
Solved it, easy as pie and now that I think about it, it's the solution listed in user PirateKitten's answer - instead of "checking off" the checkboxes besides the unread messages like my second idea, simulate clicks on those checkboxes instead. Works like a charm and here's the code, which you can run in Chrome's console while using Gmail (doesn't need jQuery btw):
var unreadMessages = document.getElementById('canvas_frame').contentWindow.document.querySelectorAll('tr.zE input');
var numMessages = unreadMessages.length;
while ( numMessages-- ) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent( 'click', true, true );
unreadMessages[numMessages].dispatchEvent(clickEvent);
}
Here's my full script that you can run inside your Chrome console (or turn it into an extension/userscript) to change the default behavior of the checkbox from selecting ALL messages to just the unread messages only:
var hasUILoaded = setInterval( function() {
if( document.getElementById('canvas_frame').contentDocument.getElementsByClassName('J-Zh-I J-J5-Ji J-Pm-I L3') ) {
clearInterval( hasUILoaded );
setTimeout( function() {
var content_frame = document.getElementById('canvas_frame').contentDocument;
var chkbox = content_frame.getElementsByClassName( 'J-Zh-I J-J5-Ji J-Pm-I L3' );
var chkbox = chkbox[0].childNodes[0];
var unreadMessages = content_frame.getElementsByClassName('zE'); // DOM structure: <tr class=zE> <td> <img><input> </td> </tr> so we add ".childNodes[0].childNodes[1]" whenever we want to access the check boxes of each message.
var allMessages = content_frame.getElementsByClassName('zA');
chkbox.onclick = function() {
if( chkbox.checked ) {
var numUnread = unreadMessages.length;;
var numAll = allMessages.length;
setTimeout(function () {
if( allMessages[0].childNodes[0].childNodes[1].checked ) {
while ( numAll-- ) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent( 'click', true, true );
allMessages[numAll].childNodes[0].childNodes[1].dispatchEvent(clickEvent);
}
}
}, 10);
setTimeout(function (){
if(!unreadMessages[0].childNodes[0].childNodes[1].checked) {
while ( numUnread-- ) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent( 'click', true, true );
unreadMessages[numUnread].childNodes[0].childNodes[1].dispatchEvent(clickEvent);
}
}
}, 30);
}
}
}, 100);
}
}, 300);

Javascript click function

I've got some code which works fine in IE but unfortunately not in Google Chrome/Firefox.
It relies upon calling a click() event on a button from javascript. Reading around it seems that this is an IE specific extension (doh). Is there any way I can do a similar thing in chrome + firefox? To clarify, it's executing the click event on a specific button, not handling what happens when the user clicks on a button.
Thanks
The code for those who asked for it:
function getLinkButton(actionsDiv)
{
var hrefs = actionsDiv.getElementsByTagName("a");
for (var i=0; i<hrefs.length; i++)
{
var id = hrefs[i].id;
if (id !=null && id.endsWith("ShowSimilarLinkButton"))
{
return hrefs[i];
}
}
return null;
}
function doStuff()
{
//find the specific actions div... not important code...
var actionsDiv = getActionsDiv();
var linkButton = getLinkButton(actionsDiv);
if (linkButton != null)
{
if (linkButton.click)
{
linkButton.click();
}
else
{
alert("Cannot click");
}
}
}
I don't really want to use jQuery unless absolutely necessary
I think you're looking for element.dispatchEvent:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
I read your question as "I'm trying to fire the onclick event for my button", whereas everyone else seems to have read it as "I'm trying to handle an onclick event for my button". Please let me know if I've got this wrong.
Modifying your code, a proper x-browser implementation might be:
if (linkButton != null)
{
if (linkButton.fireEvent)
linkButton.fireEvent("onclick");
else
{
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
linkButton.dispatchEvent(evt);
}
}
onclick attribute should be crossbrowser:
<input type="button" onclick="something()" value="" />
EDIT
And there was this question that seems to be about the same problem: setAttribute, onClick and cross browser compatibility
onclick="methodcall();" works for me fine...
you can use onClick attribute or if you need more functionality have a look at jQuery and events it offers: http://api.jquery.com/category/events/

Categories