Display the corresponding div when the span class is updated

If I have two span elements with class "selected" changing width based on selection, I just need to determine when span2 is selected.

<span class="swatch swatch-image span1">
<span class="swatch swatch-image span2 selected">

I want to detect which span is selected (has class "selected") and then show or hide a div elsewhere. Is this possible?

I've attempted the following approach:

let targetNode = document.getElementsByClassName('swatch swatch-image span2 selected');

const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };

const callback = function(mutationsList, observer) {
    for (let mutation of mutationsList) {
        if (mutation.attributeName === "class") {
            var classList = mutation.target.className;
            if(/red/.exec(classList).length > 0) {
                console.log('Found match');
            }
        }
    }
};

const observer = new MutationObserver(callback);

observer.observe(targetNode, config);

observer.disconnect();

Is MutationObserver the correct method to listen for the selected span? I am not very familiar with javascript, do I need to call MutationObserver in a certain way after setting up the code?

Answer №1

Locate the nearest container that encloses the spans and assign the task

window.addEventListener('DOMContentLoaded',() => { // once the page is fully loaded
  const container = document.getElementById('someContainer'); // adjust as necessary 
  container.addEventListener('click', (e) => {
    const tgt = e.target.closest('span.swatch');
    if (!tgt) return; // not a swatch
    console.log(tgt.textContent, 'clicked')
    document.getElementById('showWhenSpan2').hidden = !tgt.matches('.span2')
  });

// somewhere else beyond your reach
  document.addEventListener('click', (e) => {
    const tgt = e.target.closest('span.swatch');
    if (!tgt) return; // not a swatch
    document.querySelectorAll('span.swatch').forEach(span => span.classList.toggle('selected',span===tgt))
  });



});
.selected { border: 1px solid red; }
<div id="someContainer">
...

<span class="swatch swatch-image span1 selected">Span 1</span>
<span class="swatch swatch-image span2">Span 2</span>


...
</div>

<div id="showWhenSpan2" hidden>Shown when span 2 is clicked</div>

Answer №2

Thanks to @mplungjan for the fantastic solution. The code is so tidy and efficient. Much appreciated. I managed to set the id of the parent div of span.swatch, but I needed to find the nearest div that I wanted to toggle hide/show because I needed to hide/show the entire tr element:

window.addEventListener('DOMContentLoaded', () => { // when page has loaded
  const container = document.getElementById('someContainer'); // adjust as necessary
  const container2 = document.getElementById('someOtherContainer'); // searching for the tr element's parent div
  const tr = container2.closest('tr');
  if (!tr) return;
  tr.style.display = "none";
  container.addEventListener('click', (e) => {
    const tgt = e.target.closest('span.swatch');
    if (!tgt) return; // not a swatch
    if (!tgt.matches('.span2')) {
      tr.style.display = "none";
    } else {
      tr.removeAttribute("style");
    }
  });
});

This is an updated version of the code to initially hide the <tr> and then toggle between display: none and removing the style attribute when the span2 element is clicked

Turns out, Javascript isn't as daunting as I had thought

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

Using Jquery to Switch Pages

Recently, I've been experimenting with using hashes to create animated transitions between pages. Interestingly, the first page that loads (the home page) fades in and out seamlessly. However, when I attempt to navigate to another page, specifically t ...

What is the best way to utilize Vue in order to automatically scroll to the newest message whenever a new message is added?

I've been struggling to figure out how to make the window automatically move to the bottom of the blue block whenever I input a new message. I haven't been successful so far. Can anyone help me achieve this feature? Thank you in advance. Check o ...

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Strategies for Structuring Django and JavaScript Codebases

I'm grappling with the best way to structure my javascript and django code. Previously, I would include my page-specific javascript directly in the template file within a <script> tag. However, as my javascript code grew, this approach led to a ...

Using a Component's Variable in Another Component in React Native

Hello there! Thank you so much for offering your help. I have a component called PlayerWidget and would like to utilize its state variable isPlaying value in the AlbumHeader Component. Here is the code for the PlayerWidget: import React, { useContext, use ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

Upon invoking useEffect, the information is displayed, only to encounter an error when attempting to access

After fetching data from a 3rd party API and logging it in the console, I encounter the error message Uncaught TypeError: Cannot read properties of undefined (reading 'tweet_results'). Despite having conditions in place, the data does not display ...

Leveraging ng-class for designing a favorite symbol

How can I implement ng-class to toggle an icon when it is clicked, taking into account whether it is stored in local storage? For example, changing the favorite icon from outline to solid upon user click. Below is my current implementation using ng-class ...

What are the different ways to share data between components in React?

There are two components in my code, one named <Add /> and the other named <Modal>. The <Add /> component has a state for handling click events. Whenever the <Add /> component is clicked, the state is set to true. I need to utilize ...

Using Vue.js to toggle rendering based on checkbox selection

Struggling to conditionally render form elements in Vue based on user input. I can do this with VanillaJS or jQuery, but struggling to implement it with Vue's built-in conditional directives. Using single-file components with the webpack template from ...

Detecting the presence of a mobile keyboard on a website: strategies and techniques

After implementing the code below, I noticed that nothing happens when the keyboard is visible. Despite my efforts to troubleshoot, it seems that window.screen.height remains unchanged. class TestPage extends React.Component { constructor(props) { ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Is it possible to access the chrome://webrtc-internals/ variables through an API in JavaScript?

I couldn't find any information about how to access the logged variables in chrome://webrtc-internals/ on google. There is not even a description of the graphs available there. I am specifically interested in packetsLost, googCurrentDelayMs, and goo ...

JavaScript Document Object Model: Locate an element with a class that is either similar to or includes a specific substring

I am facing a situation where I need to locate a wrapper element with a specific class name that includes a random id, such as wp-rgtayfu-fxyjzw-wrapper. The class will always have the substring wrapper in it, and there is only one element in the document ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...