CSS button pressed

I came across a helpful discussion on the topic of CSS for pressed buttons, which provided some answers that I found useful. The link to the discussion can be found here: Pressed <button> CSS.

Currently, I have a button within a link and I would like it to retain its style after being pressed. Additionally, I want the button to revert back to its normal style when I click elsewhere on the page.

Here is the code snippet I am working with:

jQuery('.btnpublish').click(function(){
   jQuery(this).toggleClass('active');
});
.btnpublish{
background-color: #7f8c8d;
border: 1px solid #7f8c8d;
font-weight: bold;
}

.btnpublish:hover{
background-color: #3498db;
border: 1px solid #3498db;
}

.btnpublish:active{
background-color: #3498db;
border: 1px solid #3498db;
}

.btnpublish.active{
background-color: #3498db;
border: 1px solid #3498db;
}
<ul class="" role="tablist">
<li class="active listlayer6publish"><a class="btn btn-dark btnpublish" href="#vtab1" role="tab" data-toggle="tab"> Sports</a></li>
<li class="listlayer6publish"><a class="btn btn-dark " href="#vtab2" role="tab" data-toggle="tab"> Santé</a></li>
</ul>

Currently, the button retains its active style after being pressed, but I would like it to revert back to its normal style when I click anywhere else on the page.

Answer №1

Using hidden radio inputs with labels can simplify the process. I have updated the jQuery, although it is not necessary for the desired effects. You can refer to this POST for more information.

$(function() {
  $('.btn').on('click', function(event) {
    $(this).addClass('active');
    $('.btn').not(this).removeClass('active');
  });
});
.tablist input[type="radio"] {
  display: none;
}
.tablist label {
  display: inline-block;
  background-color: #ddd;
  color: grey;
  padding: 3px 6px;
  font-family: Arial;
  font-size: 16px;
  border: 1px inset grey;
  border-radius: 6px;
  cursor: pointer;
}
.tablist input[type="radio"]:checked + label {
  background-color: transparent;
  color: blue;
  border: 1px inset blue;
}
fieldset {
  width: -moz-fit-content;
  width: -webkit-fit-content;
  width: -fit-content;
  border-radius: 6px;
}
.btn {
  text-decoration: none;
  /* Update 'none' to 'auto' when implementing the code */
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="tablist">
  <input type="radio" id="r1" name="rad" data-toggle="tab" checked>
  <label for="r1" class="tag">
    <a href="#" class="btn active" data-toggle="tab">Sports</a>
  </label>

  <input type="radio" id="r2" name="rad" data-toggle="tab">
  <label for="r2" class="tag">
    <a href="#" class="btn" data-toggle="tab">Health</a>
  </label>

  <input type="radio" id="r3" name="rad">
  <label for="r3" class="tag">
    <a href="#" class="btn" data-toggle="tab">Celebration</a>
  </label>
</fieldset>

Answer №2

Here is a suggestion:

 Try using this code snippet with jQuery:

 jQuery(document).click(function () {
            jQuery(".listlayer6publish").each(function () {
                if (jQuery(this).hasClass("active"))
                    jQuery(this).removeClass("active");           
            });

Answer №3

To obtain the desired functionality, you can make use of the following CSS code:

.btnpublish:focus {
background-color: #3498db;
border: 1px solid #3498db;
}

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

Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs Below is my db file setup: import admin from "firebase-admin"; import serviceAccount from "./serviceAccountKey.json"; if (!admin.apps.len ...

Implementing JSON data presentation in Laravel: a step-by-step guide

I have implemented an AJAX call to retrieve data from the database in JSON format, but I am facing difficulties displaying it on the view. Below is my AJAX code: $(document).ready(function() { $("#inProgress").click(function(e) { e.prevent ...

Update with the string before it in a JSON list

Within a JSON file, I came across an array that requires the 'TODO' placeholder to be replaced with the entry above it. To elaborate, the initial "TODO" should be substituted with "Previous question" and the subsequent one with "Next question". ...

No results found for the xpath within the <p> tag

I'm currently using selenium.webdriver chrome to scrape data from my website, and I need to extract the location details of visitors. Although I have successfully identified the <p> tag that contains 'location', it is returning None. ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Unfortunately, Node Sass does not have compatibility with your current environment, which is Windows 64-bit with an unsupported runtime

Having been a regular user of Node.js to utilize gulp and sass for my HTML projects, I recently encountered a new issue. An error message stating "Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (57)" has no ...

What is causing my jQuery to only impact the initial item in my iron-list?

How can I create a toggle effect for the left border of an iron-list entry in Polymer when clicking on it? I found some jQuery code that adds the border to the first entry clicked, but I need help extending this functionality to apply to all list entries ...

What is the best way to update the switchery checkbox after it has already been initialized?

I have set up the switchery using the code snippet below. var ss_is_schedule_edit = document.querySelector('.ss_is_schedule_edit'); var mySwitch = new Switchery(ss_is_schedule_edit, { color: '#8360c3' }); However, I am unable to toggle ...

Disable the dragging of a draggable div when another div is dropped inside

In my view, I have displayed reservations and tables as div elements. The tables are draggable and droppable, while the reservations are only draggable. My goal is to be able to drag a table to a desired position and then place a reservation on it. Once th ...

Every now and then, Ajax gets stuck

My website uses this code to request new chat messages and display them, but I've been running into an issue where it freezes at times and stops fetching new messages. (function worker() { $.ajax({ url: '/client_message.php?get_messa ...

Unable to access Twig variable in the AJAX success function after submission

My situation involves a form being sent via ajax in POST. Once the controller verifies that the form is valid, it replaces the initial form with another one inside the userForm div using the ajax success function. Upon inspection of the HTML code, I observ ...

In jQuery, you can arrange an array in order and retrieve the first key

I have an array with key-value pairs and want to sort it by value, then retrieve the key of the first value. var obj = { fruit:5, vegetable:3, meat:7 }; var tempArr = [ ]; $.each(obj, function(key, value) { tempArr.push({k: key , v:value}); }); tempArr.s ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

What is the process for retrieving randomized data using mongoose?

I recently came across the mongoose-random package which allows for retrieving a JSON array of random records using mongoose. My goal is to retrieve three random records with a specific field. Despite reviewing the documentation, I have yet to find a work ...

What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue w ...

Managing the URLs of single page applications

Typically in a Single Page App (SPA), there is usually one main page that contains a side navigation menu with various anchor tags. These anchor tag URLs are managed by the angular/react/sammy js router, and the content of the main section is updated based ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Automatic Numeration in Jquery with Ordered Lists

I am in the process of using JQuery to automatically number an OL list. My goal is to create a list that looks like this: apple 1.1 green apple 1.2 red apple 1.3 red apple orange 2.1 orange juice 2.2 etc Please assist me in achieving this. $(&a ...