Javascript - EventListener triggers responses to clicks on the entire span on both its left and right sides

I recently delved into the world of JavaScript and decided to challenge myself by creating a TicTacToe game for educational purposes.

If you're curious about what my simple game looks like so far, here's a link to it:

In the game, I prompt the user to choose either "X" or "O" to begin. Initially, I had an "onclick" function embedded in the HTML code, but I learned through research that this is considered poor practice within the industry.

The previous setup with "onclick" directly in the HTML - like

<div class="XO" onclick="userChoice">
- made it straightforward for users to select their choice (X or O) accurately.

However, when I attempted to implement an event listener instead, things got a bit messy. The accuracy of choosing between X and O diminished, as clicking slightly to the left of "X" or to the right of "O" caused unexpected selections. Can anyone provide suggestions? You can view my mini project to see the current implementation.

Below is the JavaScript snippet using an EventListener:

document.addEventListener('DOMContentLoaded', function(domReadyEvent) {
  //observe clicks on the document
  document.addEventListener('click', function(clickEvent) {
    if (clickEvent.target.className.indexOf('X') > -1) {
      alert('clicked on X');
      //handle click on X
    } else if (clickEvent.target.className.indexOf('O') > -1) {
      alert('clicked on O');
      //handle click on O
    }
  });
});

I aim to accomplish this strictly within JavaScript. While I have knowledge of HTML, CSS, and more complex languages like C/C++, my experience with JS is fairly limited.

Additionally, I encountered an issue where "O" wasn't being selected. Thanks to some help, the problem turned out to be related to assigning a proper class to "O":

The issue is that you have not set a class for O

It should be: O

Answer №1

The problem lies in the fact that a class has not been specified for

<span id="O" )"="">O</span>

It should be:

<span id="O" class="0")"="">O</span>

(and it is recommended to use either class or id - not both)

In response to your other query, it is preferable to target elements like:

var naught = document.getElementById('0');

naught.addEventListener('click', function(clickEvent) {
  alert('clicked on 0');
  // handle 0 event
});

instead of using those indexOf checks

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

I am getting an undefined response when attempting to retrieve documents from a database using Mongoose

My goal is to develop a function that takes two arguments, username and email. If either of them is already in the database, the user should not be able to register. function checkAll(username, email) { let num = 0; User.find({}, (err, result) => { ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...

Does CSS Horizontal Padding Percentage Stop Relative to Element Once Maximum Width is Reached?

I'm currently in the process of developing my latest portfolio website at and I'm facing a perplexing padding dilemma that has left me stumped. The approach I'm taking with the layout involves each row of content consisting of both an outer ...

Angular auto suggest feature

I am working with a dropdown in Angular that contains JSON data. The data is stored in a List named options and I need to display the name field in the dropdown list. My current task involves implementing an autocomplete search feature for this dropdown. ...

Error found when combining a stopwatch with the react useState hook and setInterval, causing an additional interval to start when the stopwatch

I have implemented a stopwatch feature that includes start and pause buttons. The start button triggers setInterval while the pause button calls clearInterval. Initially, pressing start and then pause works correctly. However, if you press start again afte ...

reactjs function continually returning undefined

My approach is rather simple. It involves iterating through an array of objects and retrieving the object with the specified id in the parameter. Here's how it looks: returnValueToDelete(id) { this.state.rows.map(function(value) { if (value ...

"Enhance your website with a dynamic hover effect and striking letter spacing in

In the div below, there is a span with the following code: <div class="mission-button"><span class="mission">view our mission</span></div> Accompanied by this CSS: .mission-button::before { content:'&ap ...

When using server-side rendering in React with AJAX, an error may occur if trying to call setState

In order to display data to the user, I rely on the response from the AJAX request as I store all necessary information in the database. My component GenericPage.jsx: export default class GenericPage extends React.Component { componentWillMount() { ...

Oops, seems like there was a problem with parsing the

I have encountered an issue when trying to decode the value of a PHP array sent as JSON format. Here is how I created the array: $ads = $atts['ads']; if (sizeof($ads) > 0) { foreach($ads as $social_item) { $sdbr = $social_ ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Introducing a fresh new feature incorporating various div elements through the power of JQuery

Why am I unable to retrieve the text of the newly added child divs? I am using JQuery to dynamically add these elements. Here is my sample fiddle: JSFIDDLE Could someone please guide me on what mistake I made? Javascript Code: var counter = 0; $("butto ...

How can I import the raw JSON data from a table into a pandas DataFrame?

I am attempting to extract the JSON data and convert it into a dataframe from: "" , which is the original data displayed in a table at the bottom of this page "" The content on the JSON page seems to be basic JSON data like"[{\"SECURITYCODE\":& ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

Implementing a restriction on the highest page number possible and including navigational buttons for moving between

I have successfully created a pagination system using a text file as the database instead of relying on mySQL. However, I am facing an issue with limiting the maximum page numbering at the bottom of the page. Is there a way to restrict the page numbers dis ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Enforce multiple npm modules to use a common dependency

Apologies for the beginner question, I am just starting out with npm and front end development. I have a library (A) that needs to be a singleton but requires initialization to pass start up configuration. Additionally, I have a library B which has libra ...

Manipulate input fields dynamically with JavaScript

I am currently working on a functionality that involves generating an alert button based on a selection from a drop-down menu. The JavaScript part of the code is able to successfully read and send the values from the <select> drop-down as intended. H ...