3

I've been trying to make the game Battleship in JavaScript for a school assignment, and I'm stuck trying to create the opponent AI. I've created an event for when I click a cell in the grids:

function addListener(evt) {
    evt.addEventListener('click', function(){
        //bunch of code
    });
}

Now I run this function addListener every time I create a new cell in the grid in my nested for loop:

yourCell.setAttribute('id', evt + String(a) + String(b));
addListener(yourCell);

What I want now is for the opponent to run this click event when I've made my turn, so I wrote this just to test out the fireEvent function:

function enemyTurn() {
    document.getElementById('yourGrid00').fireEvent('onclick');
}

According to the second code example, I set the ID of the cell to 'yourGrid00', which I've confirmed by inspecting the html code after the JavaScript code has been run, and the function enemyTurn() will never run before each cell has been created and assigned an ID.

What I do not understand is that I get the following error on the fireEvent line:

Uncaught TypeError: undefined is not a function.

Does anyone know what I'm doing wrong?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Torstein Røsok
  • 83
  • 1
  • 1
  • 6

1 Answers1

3

fireEvent is a really old method which is only supported on Internet Explorer versions 8 and lower. You should instead use dispatchEvent if you want to handle up-to-date browsers.

Dispatches an Event at the specified EventTarget, invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) apply to events dispatched manually with dispatchEvent().

You have to create the Event manually though - you can't just call dispatchEvent('onclick'). I've pulled the first bit of the following code from this answer.

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
    false, false, false, false, 0, null);

function enemyTurn() {
    document.getElementById('yourGrid00').dispatchEvent(evt);
}

JSFiddle demo.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Thanks a lot! This seems to work :) I was just googling how to simulate a click and I stumbled upon fireEvent and found documentation on I thought it was still in use. – Torstein Røsok Oct 13 '14 at 08:54
  • Care to explain what the deal with all the attributes of the initMouseEvent is about? – Torstein Røsok Oct 13 '14 at 08:54
  • @TorsteinRøsok these set up what the mouse event is, where the event happened and a few other details. MDN has documentation on it here: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent. `event.initMouseEvent(type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);` – James Donnelly Oct 13 '14 at 08:58