What is the process for including a class along with a data attribute?

Working on implementing data buttons, struggling to make the function operational. Attempting to assign a class to an element through a data attribute and corresponding ID, then wanting to prevent event propagation with the button contained within the subject.

This is what has been achieved so far:

HTML:

<div class ="subject" id="subject1">
    <button class="remove">Remove</button>
    The Subject
</div>
<div class ="subject"  id="subject2">
    <button class="remove">Remove</button>
    The Subject 2
</div>
<div class ="subject" id="subject3">
    <button class="remove">Remove</button>
    The Subject
</div>

<button class="trigger" data-subject="subject1">Trigger</button>
<button class="trigger" data-subject="subject2">Trigger</button>
<button class="trigger" data-subject="subject3">Trigger</button>

CSS:

.active {
    color:red
}

JS:

var subject = document.querySelector('.subject');
var trigger = document.querySelector('.trigger');
var remove = subject.querySelector('.close');
var data = trigger.getAttribute("data-subject");

var datajs = (function () {

    function init() {

    [].forEach.call(trigger),function(btn) {
    btn.onclick = function() {this.classList.add("active");}

    });

     remove.addEventListener('click', function (ev) {
     ev.stopPropagation();
     removeModalHandler();
    });
 });
     }

    init();

})();

View the fiddle here: http://jsfiddle.net/tNS62/1/

My expertise in JS could use some improvement, evident from the code.

Answer №1

Give this a try. Start by selecting all the buttons :

var triggers = document.querySelectorAll('.trigger');
var removes = document.querySelectorAll('.remove');

Next, we add functionality to each button :

for (var i =0; i < triggers.length; i++) {
    var btn = triggers[i];
    btn.addEventListener('click', function () {
        var id = this.dataset.subject;
        document.querySelector('#' + id).classList.toggle('active');    
    }, false);
}

We use the dataset feature to get the attached id, then locate and toggle the active class on the corresponding element.

A similar approach is taken for the remove buttons as well.

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 specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

I have to convert a JSON string that I received from a server into a particular JavaScript object

Hey everyone! I wanted to share some code I've been working on: $.ajax({ url: '@Url.Action("GetMerchantUsers", "Merchant")', dataType: 'json', success: function (json) { var mappedTasks = $.map(JSON.parse(json ...

Issue with host header detected in MERN stack configuration

"proxy": "https://mango-artist-rmdnr.pwskills.app:5000", While attempting to establish a connection between my frontend and backend, I encountered an issue with an invalid host header. The backend is operating on port 5000, and the fr ...

Button that triggers HTML Audio play when clicked

Is it possible to have audio play when Button 1 is clicked, but then pause or stop if Buttons 2 or 3 are clicked instead? <a href="#" class="button1">Button 1</a> <a href="#" class="button2">Button 2</a> <a href="# ...

Vue.js - Duplicate Navigation Error When Redirected to a New Page

I'm facing an issue with Vue.js and the NavigationDuplicated error. As I work on a web application that involves navigation across various pages, I encounter the "NavigationDuplicated" error unexpectedly. Even though I'm not attempting to naviga ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Using Three.js to define the anchor point for rotation

I am trying to create a cone that can rotate around its top point, where the cone's thickness is at its smallest. I have been unable to determine how to set the rotation point for this movement. var coneGeometry = new THREE.CylinderGeometry(1000, 0, ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Encountering difficulties in accessing files displayed by serve-index in Express

My Node.js server using Express seems to be working fine for displaying directory contents, but I'm running into an issue when trying to access individual files. After clicking on a file listed in the directory, I keep getting an error message that sa ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

What causes MySQL connection to drop unexpectedly in a Node.js environment?

Currently, I am working on developing a Facebook chatbot using Node.js and have implemented a MySQL Database to store data. Everything seems to be working fine, but I have come across a query - should I be closing the database connection? I attempted to c ...

Host app is failing to render shared components in SSR

Encountering an issue while implementing SSR with module federation? Check out my code example Steps to Begin: Run yarn install:all command Execute yarn shell:server:build task Start the server using yarn shell:server:start Initiate remote services with y ...

The palindrome checking function is malfunctioning and needs to be fixed

I have attempted to create a function to determine if a number is a palindrome, but it seems to be malfunctioning. The concept is simple - splitting the number into two halves, comparing them, and reversing one half to check for symmetry. function palin ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

Performing operations on an array: What method do you favor and why? Is there a more efficient approach?

What is the most effective method for checking if an element exists in an array? Are there alternative ways to perform a boolean check? type ObjType = { name: string } let privileges: ObjType[] = [{ name: "ROLE_USER" }, { name: "ROLE_ ...

Transfer your documents effortlessly as soon as they are

I am having trouble implementing an automatic file upload feature without the need for a separate upload button. Below is the code I have so far, excluding the irrelevant CSS. //html <!-- some codes here--> <input type="file" id="f ...

Transferring streaming data from Node.js to an ElasticSearch database

Currently, my Node.js script is extracting data from a large USPTO Patent XML file (approximately 100mb) to create a patentGrant object. This object includes details such as publication number, country, date, and type of patent. I am working on storing a ...

HTML Navigator encountering Javascript Anomaly

Here is the code snippet I'm working with: driver = new HtmlUnitDriver(); ((HtmlUnitDriver) driver).setJavascriptEnabled(true); baseUrl = "http://www.url.com/"; driver.get(baseUrl + "/"); ... However, whenever I ...