Changing the background color of a div after a mouse click

Recently, I attempted to change the background color of a div after clicking it using only CSS. I experimented with :visited, :focus, and .visited classes in CSS, but unfortunately, none of these methods worked. I am wondering if there is a solution to apply a background color to a div after clicking on it using just CSS, with no hover effect involved.

Answer №1

If you're not familiar with javascript, here's a simple solution for you.

<div style="background-color: green;" onclick="this.style.background='yellow'">
<p>Click here to change the color from GREEN to YELLOW</p>
</div>

Answer №2

One clever solution using only CSS involves the checkbox hack

input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
  opacity: 0;
}

div {
  position: relative;
}

label {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
}

input[type=checkbox]:checked ~ div {
  background: magenta;
}
<input type="checkbox" id="checkMeOut">
<div>
  <label for="checkMeOut">test</label>
  i will change background-color
</div>

First, set up the HTML (checkbox input, the div you want to change, inside the div add a label linked to your checkbox)

Second, in the CSS, hide the checkbox in any way you want.

Position the label absolutely, giving it a height and width equal to the div's dimensions so when you click anywhere on the div, you click on the label and thus activate the checkbox giving it :checked status

Then, using the general sibling connector ~, give any style you want to the div

Let me know if it works for you

Answer №3

You can achieve this effect in CSS by utilizing the :target pseudo-class:

[id="bar"] {
   width: 8em;
   height: 8em;
   background-color: blue;
   transition: 200ms;
}

[id="bar"]:target {
  background-color: yellow;
}
<a href="#bar">
  <div id="bar"></div>
</a>

Answer №4

Here's a simple tip for you:
1- Assign an id or class to the div.

<div class="my-div">lorem ipsum</div>

2- Use the id or class to target the div when a click event occurs in your JavaScript file.
3- Feel free to customize as needed :)

$('.my-div').on('click', function () {
  $(this).css('background-color', 'yellow');
});

Hope this tip comes in handy, best of luck! :)

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

Styling a modal popup using session storage in CSS

I recently created a modal popup using CSS by following a helpful tutorial that can be found at this link: Now, I am curious about how to store the value entered in a textbox as session data. I came across some code in another tutorial that demonstrated h ...

Alt and title attributes for images are getting mixed up when there is a space in between

Every time I include a space in the alt tag of my image, it completely distorts the entire <img> line. For example, if my image title is Windows 10, specifically related to today's news. Let's assume my image tag reads Windows 10 officiall ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Show a table when a button is clicked using Javascript

Undertaking a project called: Tennis Club Management involving javascript, HTML, CSS, and bootstrap. The project includes a Login Page (index.html) and a Manage Players Page (managePlayers.html). Within the managePlayers.html, there are two buttons - Add P ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

How to turn off the default print media query in Zurb Foundation 5 without relying on SASS

I've been having trouble with printing website pages that are built using Zurb Foundation 5. Whenever I try to print or preview the page, it defaults to the `medium` grid size and looks different from how it appears on the desktop version. I've ...

Improve the parallax effect in your React component

Do you have any tips on smoothing out the scrolling animation for a React component with a simple parallax effect? I tried using requestAnimationFrame() in vanilla JS, but it doesn't seem to work well within the React component's rendering cycle. ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

Iterating through an SVG path multiple times

If I have the arrow below and I want to place it at various locations within the svg: <svg width="400" height="400"> <path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" /> <path transform="translate( ...

Is the button not aligned properly with the email input field?

<div class="subscribe__form--action--btn"> <form action="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32545b5e5b5746545C5B5356477F54585850"> </a>" meth ...

How can I make an image fill the container with CSS zoom effect

My website features a full viewport image as the background beneath the Nav Bar. I am looking to achieve a specific effect on mobile where the image is zoomed in and centered without distortion, allowing some of it to still be visible as a background. The ...

Enhancing the Syntax of If and If Else in Jquery Functions

I'm struggling to simplify and optimize this block of code. Would appreciate any help in making it more efficient! var status = "closed"; $(document).on('click', '[data-toggle-nav]', function(event) { if ($(this) && status = ...

Can you identify the language of this HTML include code snippet?

Recently, I came across some .html files that include tags in a different format: [% INCLUDE '/path/to/footer.html' %] This bracket-and-percent-sign tag is unfamiliar to me. Does anyone know what it is used for? ...

Crop images in a canvas using a customized rectangle with the help of JQuery

I am trying to crop an image inside a Canvas element using a selection rectangle. My project utilizes jQuery and I am in search of a plugin that can help me implement this custom selection rectangle on the canvas itself, not just on images. Are there any ...

Is the accept attribute of the input not recognizing application/json as a valid input type?

My application allows users to upload files, including JSON files. While most browsers recognize file extensions specified in the accept attribute of the input element, Safari may not always behave as expected. In cases where MIME types need to be used, sp ...

Resetting JavaScript Input based on certain conditions

I have been attempting to reset the input fields for a login when the loginDiv display is set to none, but unfortunately it does not seem to be working as expected. My goal is for the input fields to reset whenever the login button is clicked and the logi ...

Use Onblur and Onfocus events in an input field that is read-only

Here is an input field: <input class="" type="text" id="Name_11_1" name="Name" value="Your name:"> I would like to modify it as follows: <input class="" type="text" id="Na ...

What is the best way to position a bigger character directly above a smaller container?

My goal is to center a single character, using CSS, in a span that is smaller than the character itself. The setup I have is: <span id="A">X</span><span id="B">Y</span><span id="C">Z</span> All three spans are styled ...

Utilize Javascript to extract and showcase JSON data fetched from a RESTful API

I'm attempting to use JavaScript to pull JSON data from a REST API and display it on a webpage. The REST call is functioning correctly in the Firefox console. function gethosts() { var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://10 ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...