Switch the div's class when the parent element is chosen

I have encountered a complex issue involving two problems for which I am unable to find a solution.

In the default state without hover or selection, this div displays with a purple border when selected. My concern is: How can I change the class of the icon (blue icon) when the parent div is selected?

Default State:

https://i.sstatic.net/XnGYO.png

Hover State (Icon) / Selected State (Parent Div)

https://i.sstatic.net/EeF0H.png

Another challenge: All divs with icons share the same class. I attempted a code that worked, but selecting one div resulted in all icon divs being selected (there are 4 divs and when one is selected, all are selected).

This is the complete code: https://jsfiddle.net/905hut4v/ (the results tab will not work as I need to paste all the code from the project which is under NDA). Foundation 6 is used, hence the SCSS include error.

JS

$(function() {

    $('form[name="form-jeitos"] .block-jeito').on('click', function() {
        $(this).siblings().removeClass("selected");
        $(this).addClass("selected");
    });

    $('.image-icon').on('click', function() {
        $(this).siblings().toggleClass('selected');
    });

    $('form[name="form-jeitos"]').on('submit', function(e) {
        e.preventDefault();
        $(this).addClass("hide");
        $('#jeito-title').addClass("hide");
        var checked = $('input:checked', $(this));
        $('#'+checked.val()).siblings().removeClass("is-active");
        $('#'+checked.val()).addClass("is-active");
    });

    $('#jeito-opcoes a.back').on('click', function(e) {
        e.preventDefault();
        $('#jeito-opcoes .is-active').removeClass("is-active");
        $('form[{"name=}"form-jeitos"]').removeClass("hide");
        $('#jeito-title').removeClass("hide");
    });

});

SCSS

.block-jeito {
    border: 2px solid rgba(1, 33, 105, 0.1);
   ... (truncated for brevity)
}
... remaining HTML content also truncated for brevity ...

By the way, in addition to the described issues, there are two other functions in the JavaScript: Upon selecting a div and clicking the submit button, the user is 'redirected' to another page by unhiding a div.

Answer №1

To achieve the toggling of icon images when the parent div is focused, you can utilize CSS selectors instead of relying on JavaScript.

Here's a simple example:

.container {
  width: 50vw;
  padding: 2rem;
  border: 2px solid gray;
}

.container .nofocus {
  display: inline;
}

.container .focus {
  display: none;
}

.container:focus .nofocus {
  display: none;
}

.container:focus .focus {
  display: inline;
}
<p>Click inside the box:</p>
<div class="container" tabindex="0">
  <div class="icon">
    <img class="nofocus" src="https://i.picsum.photos/id/841/60/60.jpg?hmac=O4KlxA1-OGoNAFLLbula_vD6LrmU4H-l-yD5kkXpmLI">
    <img class="focus" src="https://i.picsum.photos/id/453/60/60.jpg?hmac=prDxZwonQi-meeXg_btjnTrjJKw5Crr85tpKIiCP_6E">
  </div>
</div>

Answer №2

With the guidance of a seasoned front-end developer, I was able to resolve this issue.

The root cause turned out to be CSS rather than JavaScript - specifically, the JS was applying the selected style to both the main div and its child div.

Our solution involved modifying the CSS as follows:

&:hover,
&.selected {
  border: 2px solid #5F249F;
    
  .icon {
    background-color: #00C7B1;
  }
}

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

Navigating redirects in HTML parsing with Python

I am currently experimenting with submitting multiple forms using a Python script and making use of the mechanized library. The purpose behind this is to set up a temporary API. The issue I am encountering is that upon form submission, a blank page appea ...

Issue with Counting Digg Button Clicks

I can't figure out why the digg button counter isn't working. I followed the instructions but... The website in question is: . I implemented the code exactly as explained here: But the counter remains at 0. Has anyone encountered a similar iss ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Discovering the method to retrieve the value of an array in JavaScript

Currently, I am developing an Android application in Titanium Studio with a Rest API (Apigee Baas) as the backend. The data stored in the Apigee Baas includes fields such as name, address, and attendance records. When retrieving the response from the Rest ...

Session Redirect Error in Express.js

Encountering an error consistently when running my code with the pseudocode provided below (Just to clarify, my code is built on the react-redux-universal-hot-example) Error: Can't set headers after they are sent. [2] at ServerResponse.OutgoingMe ...

retrieve image source based on z-index

I found a way to retrieve the z-index value using this code snippet: findHighestZIndex('div'); function findHighestZIndex(elem) { var elems = document.getElementsByTagName(elem); var highest = 0; for (var i = 0; i < elems.length; ...

Is it possible for me to create a menu using the .row and .col classes from Bootstrap?

I attempted to create a menu using Bootstrap's cols. Something similar to this: https://i.stack.imgur.com/55xst.png However, I faced numerous challenges when trying to implement it into Wordpress and realized that it may not be the best approach... ...

using jtemplates to append content rather than replacing it

Currently, I am utilizing jtemplates as my preferred templating solution (a fantastic jQuery plugin). Replacing my asp.net updatepanels with this tool has tremendously boosted the speed of my website. The only snag I've hit is when loading user commen ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Developed a hierarchical JSON format using a JavaScript array

I am aiming to generate a properly structured nested JSON file from an array, with unique key values. Currently, I can only output the JSON without any nesting. The desired structure to be displayed in the console is : { "Key" : "data1", "header" ...

Ensure that the following div remains positioned beneath the current one

After reading through this question on Stack Overflow, about creating a responsive table with both vertical and horizontal headers, I came across this particular issue, demonstrated in this codepen example: Currently, the second table appears directly bel ...

Initiating CSS animation from the start

Having an issue with the "Start button" that plays both animation and background sounds. When I pause it, the animation does not stop where it left off and starts from the beginning again. I tried using animation-play-state: pause and animation-fill-mode: ...

A guide on displaying information in a dropdown menu using JQuery, Ajax, and Backbone.Marionette

Currently, I am utilizing backbone and marionette for a web application. My objective is to populate a drop-down menu with JSON data once an option has been selected. The process involves the user selecting their account type, triggering an AJAX request, ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Verify if the username or phone number is already in use (front end)

Is there a way to verify user or phone existence on the front-end form? I'm using Yup + Formik for all my requirements, and in my backend with Sequelize, I can check if a username or phone number already exists. passport.use( 'register&apos ...

No validation errors are currently being displayed. I am attempting to retrieve the error message when validation fails

My form validation error has suddenly stopped working. It was functioning properly yesterday, so I must have made a mistake somewhere, but I can't seem to pinpoint it. Now, when I attempt to sign up without entering any information, it just redirects ...

Compatibility problem arising from the versions of ember-precompile, ember.js, and handlebars.js

Having trouble reading the precompiled templates in my HTML due to compatibility issues between ember-precompile, ember.js, and handlebars.js. My code looks like this: Includes the following files. <script src="../js/libs/jquery-1.10.2.js"></sc ...

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...