What to do when JavaScript fireEvent isn't working as expected?

I've hit a roadblock while working on my JavaScript rendition of the classic game Battleship for a school project. I'm currently stuck on devising an AI for the opponent player. I have set up an event listener for when a cell is clicked on the playing grid:

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

Each time I generate a new cell in the grid using a nested loop, I invoke the addListener function as follows:

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

My next objective is to trigger this click event for the opponent once I have taken my turn. To test the fireEvent function, I crafted a simple enemyTurn function:

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

As per the provided example, I assigned the ID for the cell as 'yourGrid00', which I have verified by inspecting the HTML output post-JavaScript execution. Note that the enemyTurn() function is scheduled to execute only after creating and assigning IDs to all cells.

However, I encountered an error on the line containing fireEvent:

Uncaught TypeError: undefined is not a function.

Could someone please point out what I might be overlooking here?

Answer №1

fireEvent is an outdated method that is only compatible with Internet Explorer versions 8 and below. For modern browsers, it is recommended to use dispatchEvent instead.

By using dispatchEvent, you can trigger an Event at a specific EventTarget and ensure proper execution of the associated EventListeners. This method follows the standard event processing rules for manual event dispatching.

It is important to note that you must manually create the Event instead of simply calling dispatchEvent('onclick'). The code snippet below demonstrates how to create and dispatch an event, with reference to this helpful 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);
}

Explore the functionality through this JSFiddle demo.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way in Rollup.js to substitute a dependency package's imported module with a local file?

I am currently working on a JavaScript project that needs to be bundled using Rollup.js. The project depends on package A, which in turn relies on package B: "mypackage" ---import--> "A" ----import----> "B" My package ...

The v-menu closes before the v-list-item onclick event is detected

I have set up the following menu using vue and vuetify: <div id="app"> <v-app id="inspire"> <div class="text-center"> <v-menu> <template v-slot:activator="{ on }"> ...

Unable to locate child after adding element to HTML

I have been attempting to add a child element to my HTML document, and although I can see it in the source code, it doesn't display on the screen as expected. It's quite baffling. Here is the HTML code snippet: <!DOCTYPE html> <html> ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows... .menu_closed { color: red; } .menu_open { color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

Trouble installing NPM packages from Artifactory on Windows 10

Problem Description: I am utilizing Artifactory for my NPM packages. When attempting to install them on "Windows - 7", everything is functioning correctly. However, on "Windows - 10" an error is being displayed and the packages are not installing. Error M ...

Modify the href attribute of an anchor tag that does not have a specified class or

I am currently using an event plugin that automatically links all schedule text to the main event page through anchor tags, like this: <td><a href="http://apavtcongresso.staging.wpengine.com/event/congresso-apavt-2018/">Chegada dos primeiros c ...

"Utilizing multiple optional parameters in Expressjs can lead to the request handler being

Hey there, I could use a fresh perspective on this issue I'm having. I am attempting to set up a request handler that can accept 0, 1, or 2 parameters like http://localhost:3000/{seed}/{size}. The parameters "seed" and "size" should both be optional. ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

developing a stand-alone job listings feature

Our website features a job postings page that our clients are interested in incorporating into their own websites. This would allow applicants to easily apply for jobs directly on the client's site, with the information being saved in our system. One ...

Having trouble extracting data from Moz Bar through selenium using Python?

Having trouble retrieving the spam score from Moz bar using Selenium WebDriver? I've attempted various methods such as XPath, class, and tag name without success. Any assistance would be greatly appreciated: from selenium.webdriver.common.by import By ...

Inform parent component about changes in child input using Angular

In my current setup, I have a parent component that holds a data object. This data object is passed down to two child components, all of which have an onpush strategy. Each child component contains a form that updates specific properties in the data object ...

Ways to incorporate JSON web token into every query string of my requests

Just recently, I grasped the concept of using JSON web tokens. Successfully, I can generate a JSON web token upon sign-in and have also established the middleware to authenticate my token and secure the routes that fall under the JSON verification middlewa ...

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Encountering Axios CanceledError while attempting to forward a POST request using Axios

While attempting to relay a POST request from an express backend to another backend using axios, I encountered an axios error stating "CanceledError: Request stream has been aborted". Interestingly, this issue does not arise when dealing with GET requests. ...

The Sacred Chalice Trio Vertical Stretch Design

Recently, I've been working on creating a three column layout with percentage width. I stumbled upon the concept of the Holy Grail web design through some online articles and resources. To implement this layout, I referred to an example from The Perfe ...

Toggle visibility of an element when clicked

I have recently started learning about jquery. In my code, I have two p tags with classes .angle_up and .angle_down respectively. The angle_up class initially has the active class assigned to it. When a user clicks on .angle_down, I want to remove the .ac ...

Load an image dynamically within a JavaScript function

I'm currently utilizing a Javascript photo viewer plugin (found here: http://www.photoswipe.com/). My goal is to dynamically update the photos connected to the plugin as the user swipes through different images. To achieve this, I am using a Javascri ...