Toggle the class of a selected data attribute on another div when clicked

With a click event, I attempt to dynamically add/remove classes by using data attributes on another div.

Upon clicking "Text 2," the initial display of "FLAG 1" is set to none, and the background color of "DOT" should change. The association between the text elements and their corresponding flags and dots above should be maintained. I already have classes named selected and active.

//planned selector
var familyTariffSelected = '.boxy';
var builderCheckoutStep = '.container .box';
var familyTariffSelectedData = $('.builder-tariff-family.selected').attr('data-selected');
var builderCheckoutStepData = $('.builder-checkout-steps .step.active').attr('data-selected');

$(familyTariffSelected).on('click', function() {
    $(familyTariffSelected).removeClass('selected');
    $(this).addClass('selected');
});
.container{
  border: 2px black dotted;
  display: flex;
  justify-content: space-between;
}
.event-box{
  display:flex;
  margin: 20px 0;
  background-color: gray;
  justify-content: space-between;
}
.container .box .flag{
  display:none;
}
.container .box .dot{
  border: 1px solid green;
  color:black; 
}
.container .box.active .flag{
  display: block;
  background-color: green;
  color:white;
}
.container .box.active .dot {
  background-color: green;
  color:white;
}
.boxy {
  background-color: yellow;
  cursor:pointer;
} 

.boxy.selected {
  background-color: #64B246;
} 
<div class="container">
  <div class="box active" data-selected="dalib-1"><p class="flag">FLAG 1</p> <span class=" dot">DOT</span></div>
  <div class="box" data-selected="dalib-2"><p class="flag">FLAG 2</p> <span class=" dot">DOT</span></div>
  <div class="box" data-selected="dalib-3"><p class="flag">FLAG 3</p> <span class=" dot">DOT</span></div>
  <div class="box" data-selected="dalib-4"><p class="flag">FLAG 4</p> <span class=" dot">DOT</span></div>
  <div class="box" data-selected="dalib-5"><p class="flag">FLAG 5</p> <span class=" dot">DOT</span></div>
</div>


<div class="event-box">
  <div class="boxy"  data-selected="dalib-1">TExt 1</div>
  <div class="boxy"  data-selected="dalib-2">TExt 2</div>
  <div class="boxy"  data-selected="dalib-3">Text 3</div>
  <div class="boxy"  data-selected="dalib-4">Text 4</div>
  <div class="boxy"  data-selected="dalib-5">TExt 5</div>
</div>

<script src="http://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>

Answer №1

Why make things complicated when you can keep it simple?

To achieve this, you need to extract the data attribute within the event handler and then target the corresponding .box using that same data attribute.

$('.boxy').on('click', function() {
    $('.boxy').removeClass('selected');
    $(this).addClass('selected');
    
    $('.box').removeClass('active')
             .filter('[data-selected="' + $(this).data('selected') + '"]')
             .addClass('active');
});
.container {
    border: 2px black dotted;
    display: flex;
    justify-content: space-between;
}

.event-box {
    display: flex;
    margin: 20px 0;
    background-color: gray;
    justify-content: space-between;
}

.container .box .flag {
    display: none;
}

.container .box .dot {
    border: 1px solid green;
    color: black;
}

.container .box.active .flag {
    display: block;
    background-color: green;
    color: white;
}

.container .box.active .dot {
    background-color: green;
    color: white;
}

.boxy {
    background-color: yellow;
    cursor: pointer;
}

.boxy.selected {
    background-color: #64B246;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="box active" data-selected="dalib-1">
        <p class="flag">FLAG 1</p> <span class=" dot">DOT</span></div>
    <div class="box" data-selected="dalib-2">
        <p class="flag">FLAG 2</p> <span class=" dot">DOT</span></div>
    <div class="box" data-selected="dalib-3">
        <p class="flag">FLAG 3</p> <span class=" dot">DOT</span></div>
    <div class="box" data-selected="dalib-4">
        <p class="flag">FLAG 4</p> <span class=" dot">DOT</span></div>
    <div class="box" data-selected="dalib-5">
        <p class="flag">FLAG 5</p> <span class=" dot">DOT</span></div>
</div>

<div class="event-box">
    <div class="boxy" data-selected="dalib-1">TExt 1</div>
    <div class="boxy" data-selected="dalib-2">TExt 2</div>
    <div class="boxy" data-selected="dalib-3">Text 3</div>
    <div class="boxy" data-selected="dalib-4">Text 4</div>
    <div class="boxy" data-selected="dalib-5">TExt 5</div>
</div>

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

Dynamic line breaks within an unordered list

I have a requirement where I need to display the last two li elements from an ul list on a new line if the screen width is less than 625px. The code snippet below achieves this functionality: ... ... ... ... However, this code fails valida ...

The absence of a datepicker in Bootstrap has become glaringly obvious

My form includes a single date input using <input type='date' class='form-control'>. When utilizing the form-control feature from Bootstrap 5, the default white color is applied to the date picker, matching the rest of the form. ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Understanding Variable Scope in JavaScript: How Variables are Accessed in Different Functions

I've been experimenting with a script that utilizes jQuery's get function to transfer data to another page and display the returned information as an alert on the current page. My goal is to send both the search field value from an input form (wh ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

Is there a way to halt the polling process for the specific API handling the background task?

I have been using this polling function for executing background tasks. export const poll = ({ fn = () => {}, validate = (result) => !!result, interval = 1000, maxAttempts = 15, }) => { let attempts = 1; // eslint-disable-next-line con ...

Utilizing the .fadeToggle() function to create a fading effect for text, which fades in and out

I am on the verge of achieving my goal, but I could use a little more assistance with this. $('.change').hover(function() { $(this).fadeToggle('slow', 'linear', function() { $(this).text('wanna be CodeNinja' ...

Create a PHP program that utilizes MySQLi to generate a unique membership number based on user input, which can then be sent via confirmation

I am currently working on developing a registration form for a bonus card program. The form will require users to enter their information and specify if they want the bonus card printed or not. If they choose to have it printed, they will also be able to s ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

The JSON sorting functionality seems to be functioning improperly

Here is a sample of my JSON data: [ { "cash": 100, "uid": "LHy2qRGaf3nkWQgU4axO", "name": "test2" }, { "cash": 1000000, "uid": "01wFhCSlnd9vSDY4NIkx", "name": "test" }, { "cash": 500, "uid": "PBOhla0jPwI4PIeNmmPg" ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

JavaScript animation not functioning properly when height is set to "auto"

Can someone help me figure out why setting the height to "auto" in the code snippet below isn't working as expected? I want the DIV to adjust its size based on the content, but it's not happening. Any ideas on how to fix this issue would be great ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

JavaScript function that allows jQuery .val() to replace trailing decimal points

Currently, I am working on restricting the input allowed in a numeric text field. My approach involves checking the length of the input field's value, and if it is greater than or equal to the specified maxlength attribute, no further input is accepte ...

Creating a selection component in ReactJS populated with data fetched from Axios

I'm attempting to retrieve data using axios, and here's the code I've created: const fetchContactList = () => { var data = { "list_id": `${myListID}`, }; const headers = { 'Content-Type': 'applic ...

The sequence of loading styles is respected, yet Bootstrap continues to take precedence over the WordPress child

After putting together a WordPress child theme that correctly displays Bootstrap and child-styles.css in the source code, I encountered an issue: View Source Code Stylesheet Order Upon inspecting with Chrome, it's apparent that the color of my link ...

Utilizing ng-click within a tooltip

I've implemented Angular Bootstrap UI and successfully added a tooltip to my project. Snippet of HTML: <div ng-app="helloApp"> <div ng-controller="helloCtrl as hello"> <a tooltip-trigger="click" tooltip-placement="bottom" uib-t ...

Connect the hover effect to both elements

In an attempt to connect a grid of links with a vertical menu, I am aiming for a hover effect that highlights both the grid item and the corresponding menu item simultaneously. Here is my current code snippet: /* Grid */ <div class="pos-content count1" ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Utilizing jQuery to Capture Select Change Events

I am trying to automatically select a hidden option based on the value selected in a visible select. Here is my jQuery code: $(document).ready(function() { var selected_val = $('#id_foo option:selected').val(); $('#id_bar').va ...