Trouble with activating div using onclick function

Having an issue setting up an edit function on gradient swatches with active class. The active class is being set correctly in the loop, but the onclick function for the current active class is not working as expected. Here's the code snippet:

editSwatch() {
// Get the container element
let gradDiv = document.getElementById("swatch");
    gradDiv.addEventListener("click", function () {
        let current = gradDiv.getElementsByClassName("active");
        // If there's no active class
        if (current.length > 0) {
            current[0].classList.add('active');
        }
        // Add the active class to the current/clicked div
        this.classList.add('active');
        this.current.addEventListener('click', function () {
        console.log("Current Div is active");
        })
    });
},

The current swatch is highlighted with a border and works visually, but the console log message doesn't display onClick. Additionally, the active class does not persist when moving the mouse away, it needs to be persistent for editing and deleting functions.

CSS code snippet:

#bg-gradient:hover,
#bg-gradient.active {
border: solid 3px rgba(84, 112, 155, 0.7);
}

Check out the demo here

Thank you!

Answer №1

It appears that the issue lies in your usage of this.current instead of current[0]. To resolve this, you can make the following adjustments:

function editSwatch() {
 let gradDiv = document.getElementById("swatch");
 console.log('clicked dev');
 gradDiv.addEventListener("click", function () {        
    let current = gradDiv.getElementsByClassName("active");
    console.log(current);
    if (current.length > 0) {
        current[0].classList.add('active');
    }
    current[0].addEventListener('click', function () {
    console.log("Current Div is active");
    })
  });
}

editSwatch();

Give this a try and see if it resolves the issue. It seems like referencing this may be causing the problem.

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

Shrink Table Column Size with Bootstrap and Stylus to Optimize Space Usage

Currently experimenting with Bootstrap to ensure my table is responsive on a search list I am developing. However, I am facing an issue where two of my columns are taking up more space than necessary. In the image below, you can see that Date and Link colu ...

Issues with importing Vue.js test units in spec files are causing difficulties

Upon reviewing a demo project, it is evident that: src components ShoppingList.spec.js ShoppingList.vue store __mocks__ index.js index.js ShoppingList.spec.js import { __creareMocks as createMocks ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

What is the best way to assign a JavaScript string to a Java string?

This particular dropdown list allows for multiple values to be selected -- A loop has been utilized to populate the options in the list by fetching data from a database. Here is the javascript function I am attempting to implement in order to retrieve th ...

Automatically populate Bootstrap modal input with a value retrieved from an AngularJS controller

Can someone assist me with prefilling my form in a bootstrap modal using ng-model data? I attempted some methods but haven't been successful. Here is a link to the plunker with my code. I tried incorporating a resolve function with a $scope object ret ...

CSS Flexbox: Achieving Perfect Alignment for a Responsive Hamburger Navbar

This is a specific inquiry that requires your attention To begin, kindly execute the code in fullscreen mode Inspect the code and adjust it to fit within a mobile width (there seems to be an issue with responsiveness) Next, open the hamburger menu As show ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Next.js version 14 is having difficulties displaying the loading.tsx file

click here for image description Why is the loading not displaying when navigating to /profile? How can I fix this issue? export default function Loading() { // You can add any UI inside Loading, including a Skeleton. return ( <div> lo ...

Unable to successfully change the Span Class

My webpage has the code snippet below, but it's not functioning as expected. I have tried two methods to change the span's class attribute, but they aren't working. Could someone please help me identify where the issue lies? :) <script l ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...

How can you use DOM manipulation to extract input data from an <input type="file"> element?

Is there a way to retrieve the data from an <input type="file"> element, specifically if it contains an image, without utilizing an html form? Here is the HTML code: <body> <input type= "file"> </body> ...

Error: MongoDB issue - Attempting to access the 'length' property of a null value leads to a TypeError

Encountering a mongodb error when running a query. Here is the specific error: TypeError: Cannot read property 'length' of null Provided code snippet: // Establish connection to MongoDB MongoClient.connect(process.env.MONGO_URL, (error, db) ...

Having trouble with loading background images in Angular 4?

After researching extensively on stack overflow, I am still struggling to resolve this issue. The main problem I am facing is related to adding a background image to the header tag in my code. Unfortunately, no matter what I try, the background image refu ...

The Click Event is failing to trigger for a dynamically created ID within a span element

I am currently working on a Task Project. In this project, I have been adding items dynamically and generating items dynamically as well. However, when it comes to deleting items by clicking on a span element, the click event doesn't seem to work. I ...

JavaScript / jQuery load function for removing / adding items

I'm attempting to create an animation where I delete one element and then add another, repeating in a loop. I have achieved this with buttons, but I am looking for a more animated approach. $("#div1").remove(); $("#div2").prepend("Some prepended tex ...

What is the best way to handle response once an asynchronous call has been completed?

In my express.js application, I have implemented a "Pay" button on the user interface. When this button is clicked, I need the server to interact with Stripe's checkout API and wait for a response before proceeding (for example, if a card is expired). ...

"Converting HTML to JSX for Your ReactJS Component: A Step-by-Step Guide

My current tech stack includes Webpack, Redux, and ReactJS. Right now, I have a setup in my index.html, but I want to convert it into JSX format as a ReactJS component. Can someone guide me on how to do this correctly? In my index.html, within the <he ...

React.renderComponent does not exist as a valid function

After reading several articles on ReactJs for beginners, I came across a tutorial that only provided code snippets. While attempting to work on my first component, I encountered some difficulties: Here is the full code: <!DOCTYPE html> <html lan ...

utilizing a specific pseudoclass

To customize the bullets of unordered list items, I am utilizing a pseudo-class to display 4 boxes and a white right pointing arrow (▢▢▢▢▷) by default: li:before { content: "\25A2\25A2\25A2\25A2\25B7&qu ...

Filtering rows of an HTML table that contain links in the `<href>` column data in real time

When using HTML and JavaScript, I have found a solution that works well for many of the columns I am working with. You can see the details on how to dynamically filter rows of an HTML table using JavaScript here. var filters=['hide_broj_pu',&apo ...