Prevent parent element from changing color when child element is clicked

Check out my HTML:

.imageURL:active .image_submit_div {
  background-color: #ccc;
}

.image_submit_div:active {
  background-color: #e6e6e6;
}
<div class="image_div">
  <label for="id_image" class="image_submit_div">
        <h3>+ add file</h3>
        <input id="id_imageURL" class="imageURL" type="text" name="imageURL" />
    </label>
  <input id="id_image" type="file" name="image" />
</div>

The main div is image_submit_div. It changes color when clicked.

The nested element is .imageURL. I don't want the parent div's color to change when this is clicked. The code above doesn't work for that purpose.

How can I stop the parent div from changing color when the child div is clicked?

UPDATE: For more clarity, here is a link to a code snippet: https://codepen.io/kingdezz/pen/WOoPgY

Answer №1

If you try to style a parent element based on its child (or an event that occurs on the child) in CSS, it won't work. You cannot write something like child:hover parent { styles }.

CSS only works from top to bottom, so you need to use parent:hover child { styles }.

Although your question is a bit unclear, you could consider using jQuery for this purpose.

You can make use of the mousedown and mouseup events to achieve the desired effect:


$(".imageURL")
  .mousedown(function(e) {
    $(this).parent(".image_submit_div").addClass("colored");
  })
  .mouseup(function() {
     $(this).parent(".image_submit_div").removeClass("colored");
  });

.image_submit_div:active {
 background-color: red;
}
.image_submit_div.colored { 
background-color: blue;
}
.image_submit_div { 
display: block;
}

Answer №2

Implementing the Jquery methods .focus() and .blur() can be achieved in the following way:

$(function() {
  $('#id_imageURL').on('focus', function() {
    $(this).closest('label').css('background', '#ccc');
  }).on('blur', function() {
    $(this).closest('label').removeAttr('style');
  })
});
.image_submit_div {
  position: relative;
  border: 1px solid #ccc;
  display: inline-block;
  padding: 20px 50px;
  width: 55%;
  height: 320px;
  cursor: pointer;
  background: #e6e6e6;
  margin: 0 0 25px;
}

.image_submit_div:active {
  background-color: #ededed;
}

.imageURL:active .image_submit_div {
  background-color: #ededed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image_div">
  <label for="id_image" class="image_submit_div">
        <h3>+ add file</h3>
        <input id="id_imageURL" class="imageURL" type="text" name="imageURL" />
    </label>
  <input id="id_image" type="file" name="image" />
</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

Is there a way to choose only the rows that are both even and not currently hidden?

I'm looking to change the row background colors in an alternating pattern. My goal is to target <td> elements on even rows that are not hidden. This is what I've attempted: $(".results-table tr:not(.hidden-row):even") .children("td") ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...

How can I write a JavaScript function that eliminates all white spaces within a string?

Exploring ways to create a custom function that trims white spaces from the beginning and end of a string (including \n, \t) without relying on built-in methods like trim(), replace(), split(), or join() Here’s an example code snippet showcasi ...

Tips for resolving the 'node is not defined' error in the case of passing a default value

Attempting to incorporate the Trie data structure into JavaScript has presented a challenge. Within the print function, which displays an array of all words in the Trie, there is a search function that looks for words within the Trie and adds them to the a ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

the button function is unresponsive

Can someone please help me troubleshoot my jQuery code? Everything seems fine, but the generate button is not working when clicked! PS: I've searched extensively for a solution to this problem but haven't been able to find one. I've also at ...

Efforts to seamlessly combine two divisions of a business card through the use of CSS and HTML

Currently, I am working on designing a business card that includes both front and back sections. Below is the code snippet that I have been using: .business-card:hover .front{ transform: perspective(700px) rotateX(180deg); } .business-card .back{ tr ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Displaying a division when a button is pressed

Despite my best efforts, I can't seem to get the chosen div to show and hide when the button is pressed. <button id="showButton" type="button">Show More</button> <div id="container"> <div id="fourthArticle"> <i ...

What is the best way to ensure my responsive form is centered and aligned properly with all other elements on the page

Link to website This final step is all that stands between me and the completion of my website deployment. However, I am faced with a persistent issue that has me stumped. It seems that there is an unexplained margin on the left side of the contact form, ...

The page you are trying to access could not be found after attempting to upload 5

I am encountering an issue with jQuery File Upload where I am able to successfully upload files for any number of files up until 5. However, when attempting to POST 5 or more files, the server returns a 404 Not Found error. Oddly enough, POSTing only 4 fil ...

What is preventing the 'p:nth-child(1)' from functioning properly in my HTML code?

Even though I used p:nth-child(1){color: white;} in my CSS style tag, it did not produce the expected result. body { background-color: #162b85; } button, p:nth-child(1) { color: white; } <p class="center">Register your account</p&g ...

What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

Ways to modify the gap between buttons using CSS

I am faced with a design challenge on my home page. I want to add some spacing between the buttons so they are not too close to each other, but for some reason margin-top and margin-bottom properties are not working as expected. Can you help me figure out ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

Ways to simulate a class instance that is being received from a file with a different class instance

I am struggling with a specific file in my project // src/history import { createBrowserHistory } from 'history' const history = createBrowserHistory(); export default history; The variable history represents an instance of the BrowserHistory cl ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Exploring the World of Unit Testing with Jasmine and Sinon Factories

At my factory, I have implemented a getter and setter function .factory('myService', function() { var car = null; return { car: car, get: function get() { return car; }, set: function set(newCar) { car = newCar; ...