Alter the div's color when it is clicked by the user

When a user clicks on any of the divs, I want to change its background color. Additionally, I want the first div to be active by default with a colored background.

The code I am using is as follows:

.tabs.active a {
  background: black;
}
<div class="col-md-2 tabs">
  <a href="#">
    <p>First</p>
  </a>
</div>
<div class="col-md-2 tabs">
  <a href="#">
    <p>Second</p>
  </a>
</div>
<div class="col-md-2 tabs">
  <a href="#">
    <p>Third</p>
  </a>
</div>

However, the color is not changing. If anyone can identify where my code has gone wrong, please let me know.

Answer №1

While CSS alone cannot directly capture a click event, there are some clever workarounds available. One popular method involves using a checkbox:

div {
  width: 120px;
  height: 60px;
  padding: 6px;
  background-color: green;
  color: white;
  border: 5px solid blue;
}
input[type="checkbox"] {
  display: none;
}
input[type="checkbox"] + label {
  display: table;
  margin: 25px;
}
input[type="checkbox"]:checked + label div {
  background-color: orange;
  color: black;
}
<input type="checkbox" id="cb1">
<label for="cb1">
  <div>
    Click Me - Div 1
  </div>
</label>

<input type="checkbox" id="cb2">
<label for="cb2">
  <div>
    Click Me - Div 2
  </div>
</label>

By enclosing the divs in labels associated with hidden checkboxes, any interaction within the label triggers a change in the checkbox state, causing CSS styling to be applied accordingly.

The selector

input[type="checkbox"]:checked + label div
targets checked checkboxes followed immediately by labels and their enclosed div elements. It is crucial that the label directly follows its corresponding checkbox in the HTML structure.

Feel free to customize this code to better fit your specific requirements.

UPDATE: In a previous iteration of this solution, the clickable area extended across the entire parent container due to the default behavior of labels. By utilizing display: table;, this issue is resolved without compromising block-level functionality. Alternatively, you can opt for inline-block to maintain divs on the same line as needed.

Answer №2

To implement the focus Pseudo class with Tabindex, you can use the following code:

However, it's important to note that if you focus on any other element, the background style of the tabs may be lost.

.tabs>a>p:focus{ 
  background-color:gray !important;
  display:inline-block;
  color:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-2 tabs" >
    <a href="#">
        <p tabindex="1"> First </p>
    </a>
</div>
<div class="col-md-2 tabs" >
    <a href="#">
        <p tabindex="2"> Second </p>
    </a>
</div>
<div class="col-md-2 tabs" >
    <a href="#">
        <p tabindex="3"> Third </p>
    </a>
</div>

Answer №3

Utilizing the :target pseudo-class

.col-md-2:target {background-color: black;}
<div class="col-md-2 tabs" id="first">
    <a href="#first">
        <p> First </p>
    </a>
</div>
<div class="col-md-2 tabs" id="second" >
    <a href="#second">
        <p> Second </p>
    </a>
</div>
<div class="col-md-2 tabs" id="third">
    <a href="#third">
        <p> Third </p>
    </a>
</div>

Answer №4

$(".tabs").on("click", function(e){
  e.preventDefault();
  $(".tabs.active").removeClass("active");
  $(this).addClass("active");
});//
.tabs.active a
{
  display: block;
  background: black;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="col-md-2 tabs">
    <a href="#">
        <p> First </p>
    </a>
</div>
<div class="col-md-2 tabs">
    <a href="#">
        <p> Second </p>
    </a>
</div>
<div class="col-md-2 tabs">
    <a href="#">
        <p> Third </p>
    </a>
</div>

Answer №5

Give this a shot...

$(".tabs").on("click", function(){
  $(".active").removeClass("active");
  $(this).addClass("active");
});

By doing this, the .active class will be added to the clicked element and your CSS styles will take effect.

Answer №6

$(window).load(function () {
$('.nav-menu ul li a').click(function (e) {
    $('.nav-menu ul li').removeClass('active');
    $(e.currentTarget).parent('li').addClass('active');
});

});

check out this link for more information

Answer №7

It seems like there may be an issue with the CSS you provided. Here is a revised version that should work:

.tabs:active {
    background-color: black;
}

Answer №8

It seems there may be some confusion regarding whether you prefer each div to change colors independently or if only one should be highlighted.

If your goal is to have only one div selected at a time, consider implementing @Magnus Buvarp's solution using radio buttons instead of checkboxes with the same name attribute.

div {
  width: 100px;
  height: 50px;
  padding: 4px;
  background-color: #eee;
  border: 2px solid gray;
}
input[type="radio"] { /* updated to "radio" */
  display: none;
}
input[type="radio"] + label { /* updated to "radio" */
  display: table;
  margin: 20px;
}
input[type="radio"]:checked + label div { /* updated to "radio" */
  background-color: yellow;
}
<strong>Only one can be selected!</strong>

<input type="radio" name="group1" id="rb1">
<label for="rb1">
  <div>
    Click Me!
  </div>
</label>

<input type="radio" name="group1" id="rb2">
<label for="rb2">
  <div>
    No! Click Me!
  </div>
</label>

By clicking on one radio button, the other will become unselected.

The downside is that one of the two options always has to be selected once you make a choice. Consider your needs before deciding if this approach is suitable for you.

P.S. Made some minor color adjustments for no particular reason, just felt like it :)

Answer №9

If you want to toggle classes, you can use the toggleClass() method in jQuery or JavaScript (

element.classList.toggle("active")
)

$(".tabs a").click(function(){
  $(this).parent(".tabs").toggleClass("active")
});

You also need to make changes in CSS:

.tabs.active{
  background: black;
}

$(".tabs a").click(function(){
  $(this).parent(".tabs").toggleClass("active")
});
.tabs.active{
  background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2 tabs active">
  <a href="#">
    <p>First</p>
  </a>
</div>
<div class="col-md-2 tabs">
  <a href="#">
    <p>Second</p>
  </a>
</div>
<div class="col-md-2 tabs">
  <a href="#">
    <p>Third</p>
  </a>
</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

Leveraging JQuery to Invoke Partial View

I have a partial view in my /Shared folder that is defined as follows: <div id="myProducts"> @Html.Partial("_ProductsList",Model) </div> I am attempting to refresh the _ProductsList view using jQuery. Specifically, I wan ...

Is it possible to visually distinguish the selected mat-grid-tile? Particularly when they are being created dynamically

On the user interface, I have a dynamic display of mat-grid-tile within a mat-grid-list. These tiles change in number and data based on backend values. When a user clicks on a mat-grid-tile, it triggers a function that receives the tile's data. My goa ...

Steps for generating a unique division element for every javascript response

How can I dynamically create a new div for each response in JavaScript? The message is in JSON format containing all the messages sent and received. This is my JavaScript code: $.get("MessageServlet", function (responseJson) { $.each(responseJ ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Discover media sources with HTML5's getUserMedia()

I've recently developed a streaming webcam using html5. Currently, I am able to capture images with my web cam, but I'm curious if there is a way to select the media stream device from a list. For example, if I have multiple web cams connected, I ...

I encountered a ReferenceError while working on my Google Authentication code, specifically stating that the variable "id" is not defined

I've encountered an issue with authentication in my code and I'm having trouble retrieving the ID that is already created. Here's the code snippet: require('dotenv').config() const express = require("express"); const bod ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

Creating articles within a KnowledgeBase using PHP, jQuery, and MySQL

My goal is to establish a comprehensive knowledge base for our customer service department by extracting information (ideally from a mysql database) and displaying it on a webpage based on the retrieved content. Imagine a website like: ToastMaster I want ...

The text on the HTML page reads from left to right in a page that

Currently, I am facing the challenge of showing a negative number in an HTML page with rtl direction. Despite using direction: ltr, the label does not display correctly. To demonstrate the issue, I have created a jsFiddle showcasing the reverse scenario ...

Floating Crosshair within Div - Limited to Container

I'm attempting to implement a crosshair-style cursor effect on a div that houses a D3 Datamap. I've managed to achieve this using jQuery, but the crosshairs appear to extend beyond the boundaries of their parent div on the bottom and right sides, ...

Unable to display keyboard on HTML input form in webview

Can someone assist me with displaying and allowing the keyboard to show and input properly? In my simple app, I have a main screen with buttons. When a button is clicked, it opens a webview. One of the buttons opens a webview to an HTML page with an input ...

Deciphering Keycodes in Chrome for Mac OS is a must-know skill for smooth

Is there a way to prevent the '-' key from being pressed on an input field? Initially, I tried using the following solution: if(e.keycode == 189 || e.which == 189 ){ return false; } However, it turns out that both the '-' and &apos ...

Display message until response from ajax is obtained

I need assistance in displaying an error message until the ajax response is received. Here is the code I have tried: $.ajax({ url: "user.php", type: 'POST', data: $('#forgot-form').serialize(), beforeSend: funct ...

(Express JS) What is the correct way to integrate another module into my router? (I am consistently encountering an undefined reference error)

I am currently working on a basic PDF reader application that utilizes the pdf.js library from Mozilla. The user is expected to select a file, after which the website should automatically redirect to the /reader page displaying the PDF. However, I am facin ...

How can the datepicker be adjusted to display from right to left?

//Initializing the datepicker $('dob').on('click',function(){ $('.datepicker').datepicker({ "format": "dd/mm/yyyy", "autoclose": true }); }); <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Is it possible to vertically align variable length text within a container of fixed height?

One common method for centering text inside a div is to use the following CSS trick: .center-div { display:table-cell; vertical-align: middle; } The issue arises when the text within the div varies in length and I require the container to have fi ...

Incorporate a background image into input fields with Autofill on mobile browsers to override the default yellow background that obscures them

It is common knowledge that modern browsers apply a less than appealing yellow background to text fields when Autofill is used by visitors. A helpful workaround is known to override the default text and background colors, and even incorporate a background ...

Analyzing exif data during the process of uploading a batch of images

My website allows users to upload multiple images simultaneously. I want to check the EXIF rotation tag of each uploaded image in order to manually rotate the images in the browser if needed. I came across a solution for reading the EXIF rotation value of ...