1

I have a grid of divs which represents a map. I want to be able to generate click event on any of the div as I click with my mouse. I have used following code snippet with no success though I get a true return value:

var fireOnThis = document.getElementById('someID');
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, true );
fireOnThis.dispatchEvent(evObj);

I know no click is being generated because when I click with actual mouse the div gets highlighted.

Just a side question: Is it possible that one could distinguished between actual mouse generated clicks and ones generated via javascript itself and block the later ones ?(I know it sounds logically wrong but I dont know much JS so maybe.... )

Some background: I am doing this for an online gaming website where I want to automate the routine tasks by writing an extension for chrome....this part is for content script.

Edit: Perhaps I am looking at problem the wrong way..... perhaps in actual, the div is not listening for the click event, the reason div doesn't get selected in actual even when the event gets fired.....
New Question: given the event (i.e., click on a particular div) can I tell which listener/element received that event ?

Jamil
  • 2,150
  • 1
  • 19
  • 20

4 Answers4

3

My answer to this SO question presented this function, which may be useful:

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);
    }
}

Here's another SO question on this subject

Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

Technical information and code sample is available here. Demo here and here.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • In the demo you are using value of dispatched to check if event was fired or not. As I posted originally, I am getting a true response but the div doesn't get selected. can this be the case that my event is being some how blocked/filtered along the way ? – Jamil Mar 26 '11 at 08:30
  • No idea. Do you have an onclick handler set on the DIV? You might be able to check this by doing a `alert(typeof document.getElementById('someID').onclick)`. – Salman A Mar 26 '11 at 10:57
-1

why not use jquery?

$('#someID').click();

I do think that there may be ways to distinguish mouse clicks and triggered clicks: the x/y position of a triggered click may not match the position of the element clicked.

Geeklab
  • 199
  • 2
-1

use the jquery click event to fire a function. it's easier.

locoboy
  • 38,002
  • 70
  • 184
  • 260