8

I want to simulate click on GMail COMPOSE button using JS without JQuery.

Here is button:

<div class="T-I J-J5-Ji T-I-KE L3" role="button" tabindex="0" gh="cm" 
style="-webkit-user-select: none;">COMPOSE</div>

Here is my js:

var element = document.getElementsByClassName('T-I-KE')[0];
element.click();

Result:undefined in all browsers

Image: http://i.imgur.com/4IX9DZX.png

Already tried that:

var event = document.createEvent("MouseEvent");
event.initEvent("click",true,true);
var element=document.getElementsByClassName("T-I-KE")[0];
element.dispatchEvent(event);

Result:true. But nothing happens.

Image: http://i.imgur.com/pwVqukP.png

Mikolaytis
  • 861
  • 1
  • 10
  • 25

2 Answers2

11

After two days i am finally got an answer!

That button listens mouseDown and mouseUP events. Working code:

var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');
var elem = document.getElementsByClassName("T-I-KE")[0];
elem.dispatchEvent(down);
elem.dispatchEvent(up);
Albert Renshaw
  • 16,406
  • 17
  • 99
  • 182
Mikolaytis
  • 861
  • 1
  • 10
  • 25
  • Refer to http://stackoverflow.com/questions/10213703/how-do-i-view-events-fired-on-an-element-in-chrome-web-developer on how to monitor events -- it will save you a lot of head scratching :). – thdoan Mar 01 '16 at 07:26
  • 3
    This works well for some buttons (like 'compose' or 'more') but has any effect on other buttons (like 'settings' in the right corner). After few hours of monitoring events I gave up. Anyone is able to click 'settings' programatically? – Edvard Rejthar Dec 01 '17 at 16:59
-1

The function getElementsByClassName(classString) will return the elements with the class of exactly the string that you pass to it. Try using querySelector, like this

document.querySelector(".T-I-KE");

That will return the first element with the class T-I-KE. If you want ALL the elementes with that class, call the function querySelectorAll instead

Yerko Palma
  • 11,136
  • 5
  • 33
  • 56
  • I don't have issues with selecting a button. I can't simulate click on it. Here is your example: http://i.imgur.com/riFnz1o.png Result the same. – Mikolaytis Feb 12 '15 at 14:36