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 ?

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

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 ?
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).
-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.

1 Comment

Is there a way I could test it in JS console that comes in chrome ?
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.