JavaScript - Issue with the OnClick event not triggering

I encountered an issue while trying to change the class of an element using pure Javascript upon clicking it. Even though I have used similar code successfully in the past, this particular instance did not work as expected. Here is the relevant part of the code snippet -

HTML-

<div id="div" class="blue">.</div>

CSS-

.blue{
    width: 500px;
    height: 500px;
    z-index: 9876543210;
    position: absolute;
    margin-top: 20%;
    margin-left: 20%;
    -webkit-transition: all 0.5s ease-in-out;
    background-color: #24e;
}
.red{
    width: 300px;
    height: 300px;
    position: absolute;
    margin-top: 20%;
    margin-left: 20%;
    -webkit-transition: all 0.5s ease-in-out;
    z-index: 9876543210;
    background-color: #e69;
}

JAVASCRIPT-

function toggleClass(){
  this.classList.toggle('blue');
  this.classList.toggle('red');
}
document.querySelector('#div').addEventListener('click', toggleClass);

In addition, I have included a link to jQuery on the page (not sure if that affects anything). However, despite everything set up correctly, nothing happens when I click on the "div".

Please share any suggestions or solutions to help resolve this issue.

Answer №1

Incorporating jquery into your project allows you to utilize the .click() function for capturing click events on div elements. To alternate between classes, toggleClass is your go-to method. The initial class added is blue, causing red to switch back and forth with each click on the div.

$('#div').click(function(){
       $('#div').toggleClass("blue red");
})

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

Showing data in a tabular format shows the results in various columns, one after the other

I have organized my data in a table format with 5 columns. The information flows across the page horizontally, but I would like it to fill each column first before moving to the next. This makes it easier for users to scan the data vertically rather than ...

The step-by-step guide on implementing secure authentication using cookies in Next.js

I am encountering a minor issue. I am still very new to Nextjs and I am attempting to learn by creating an app. I have successfully implemented a Login system using Next, but I am facing some challenges in securing routes. After a successful login, I have ...

A guide to making API calls in node.js with JSON data in the body

I am looking to send HTTP requests to an external API service. The web server I am trying to communicate with requires specific headers and a JSON payload in the request body. After researching, I found the request package which seems promising for this ...

Leverage socket.io in various routes within a node.js application

In my Node.js application, I have various routes defined in the router.js file. Now, I want to implement socket.io in every route to enable real-time communication between my Node.js and React.js applications. However, the structure of my Node.js applicati ...

Event Triggering in CakePHP

I am struggling with the onChange event in this code snippet. I must have overlooked something because it's not functioning as expected. Can someone please point out my mistake? Your assistance is greatly appreciated: <td class="cellInput"> & ...

Implementing relationships in microservices with Prisma and NestJS

Schema for User Management service: model User { id String @id @default(uuid()) username String @unique email String @unique password String } Schema for File Management service: model File ...

Executing SendKeys on a div element with the attribute coleditable="true" in Selenium and C#

I am facing a challenge with an element that I am unable to input text into. <div class="floatstart gridcell grideditablefield" colname="Items" coltype="string" coleditable="true" val="" style="widt ...

Achieving loop functionality with a JSON JavaScript array

I'm having trouble with this code as it only retrieves the first data from the JSON and then stops processing. I've tried simplifying it by starting over, but I can't seem to figure out what's missing. It feels like there's a simpl ...

defineProps withDefaults "The type is lacking the following properties from the specified type"

I am currently working on a custom Button component with some unique functionality: <script lang="ts" setup> import { computed, ref } from 'vue'; const { type = 'button', color = 'primary', disabled = fa ...

Is there a way to retrieve information from an external URL in JSON format and display it using JavaScript on a separate HTML webpage?

I'm trying to display the value TotalPostNotificationCount from a JSON file in an external HTML using either JavaScript or PHP. The JSON data is as follows: { "DayPostCount": 1, "TotalPostNotificationCount": 7381 } This data can be found at t ...

Rotating an SVG shape a full 360 degrees results in no visible change

Currently, I am utilizing d3.js for a project and encountering an issue with rotating an SVG element 360 degrees to achieve a full spin back to its original position. If I rotate the element 3/4 of the way using the following code snippet, it works effect ...

To access the context menu popup and the first element of a row in a datatable, simply right-click on the row

Currently, I am working on writing code for a datatable where when you right-click a row, two actions should be triggered: a context menu should appear, and I need to retrieve the first cell of that row to pass it to my Ajax function. I have managed to wr ...

Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method. for (let i = 0; i < this.prodList.length; i++) { let setContent = false; for ...

Tips for submitting data to the identical ejs view or partial following utilizing res.render get?

Is there a way to display data in my EJS file that is posted after the view has been rendered using res.render()? When I try to use <% date %> in my EJS file, it throws an error saying that date is not defined. This makes sense because the value is s ...

Link several jQuery elements to a function simultaneously

Having 3 jQuery objects is my current situation: var first = $('.el1'); var second = $('.el2'); var third = $('.el3'); I am trying to attach a "change" event to all of them simultaneously, but facing some challenges :( $(fi ...

Can anyone advise on the proper way to import CSS within a React component?

I'm currently working on a React component named Comp1 and I've included a CSS file within it like so: import "./style.css"; Within the style.css file, I'm using the following line: @import "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

Delay the next loop iteration until receiving an HTTP request

I have a task where I am collecting YouTube video IDs and storing them in an array. Then, I am looping through each video ID to determine the size of that ID's thumbnail image. My challenge now is making sure my loop waits for the HTTP request to fini ...

The container in Bootstrap's CSS now appears when the navigation bar is present

Experiencing a minor issue here. I am attempting to create a layout with a navigation positioned in the top right corner, and the main content contained within a separate container below it. The problem I am facing is that the content container seems to b ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...