What is the best way to maintain the highlighting of a clicked navigation button in CSS?

.custom-highlight {
  display: inline;
  font-weight: 500;
  font-size: 15px;
}

.item-list {
  border: 1px solid #b1b8c9;
  color: $color-grey-light;
  font-size: 14px;
  display: inline-block;
  margin-right: 8px;
  padding: 5px 20px;
  border-radius: 4px;
  background-color: #ffffff;
  margin-top: 10px;
  cursor: pointer;
  &:hover {
    background-color: $color-safron;
    color: #ffffff;
  }
}
<ul class="custom-highlight">

  <li v-on:click="highlightItem" @click="selectItem('a')" :class="{ activeListItem }" class="item-list">a</li>

  <li v-on:click="highlightItem" @click="selectItem('b')" :class="{  active: isActiveClass,}" class="item-list">b</li>

  <li v-on:click="highlightItem" @click="selectItem('c')" :class="{  active: isActiveClass, }" class="item-list">c</li>



</ul>

I have 3 buttons, like a,b,c. So On clicking of every button i need to show the blue color highlighted and stay over there.

and when if user press different button, then color highlight need to move.

Answer №1

This solution has been updated to utilize Vanilla JavaScript exclusively, with the removal of VueJS syntax for clarity on how the solution works

let elements = document.querySelectorAll('.product-list')

elements.forEach(el => {
  el.addEventListener('click', () => {
    elements.forEach(el => el.classList.remove('active'))
    el.classList.add('active')
  })})
.message-show {
  display: inline;
  font-weight: 500;
  font-size: 15px;
}

.product-list {
  border: 1px solid #b1b8c9;
  color: lightgray;
  font-size: 14px;
  display: inline-block;
  margin-right: 8px;
  padding: 5px 20px;
  border-radius: 4px;
  background-color: #ffffff;
  margin-top: 10px;
  cursor: pointer;
}

.product-list:hover {
  background-color: blue;
  color: #ffffff;
}

.active {
  background-color: blue;
  color: #ffffff;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <script src="script.js" defer></script>
  <title>Document</title>
</head>
<body>
  <ul class="message-show">
    <li class="product-list">5-10</li>
    <li class="product-list">10-22</li>
    <li class="product-list">22-27</li>
  </ul>
</body>
</html>

Answer №2

<style>
.inactive{
   background-color: #ff9900;
 }
</style>

<script>
function displaySelectedOption(){
  $(":button").removeClass("inactive");
  $(this).addClass("inactive");
 }
</script>

Answer №3

Since I am a bit confused by the question, I will provide two different CSS solutions:

  • To keep the button highlighted even when not clicked, use
    a:focus { background-color: blue; //or other color }
  • If you only want the button to be highlighted while it is being clicked, use
    a:active { background-color: yellow; }
    . Hopefully this explanation helps with your HTML coding.

Answer №4

Design a class with the necessary blue styling. Next, set up an onClick event listener to addClass('blue-highlight'). If another button is clicked, removeClass('blue-highlight').

for (var i = 0; i < elem.length; i++) {
    elem[i].addEventListener("click", function(e) {
        var current = this;
        for (var i = 0; i < elem.length; i++) {
            if (current != elem[i]) {
                elem[i].classList.remove('blue-highlight');
            } else if (current.classList.contains('blue-highlight') === true) {
                current.classList.remove('blue-highlight');
            } else {
                current.classList.add('blue-highlight')
            }
        }
        e.preventDefault();
    });
};
toggleItem(document.querySelectorAll('product-list'));

Example of how it could look:

https://codepen.io/aish_0509/pen/ExmNmvB

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

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value > ...

What is the proper way to access the current value of a computed property from within its own computation method?

Our goal is to activate a query when a string reaches a length of 3 characters or more, and keep it activated once triggered. Leveraging the Vue 2 Composition API, we have implemented a reactive object to manage the status of queries: import { computed, de ...

Tips for implementing the vue-simple-spinner in your project:

I implemented the vue-simple-spinner: in my main.js: import Spinner from 'vue-simple-spinner' .... Vue.component('vue-simple-spinner', Spinner) however, when I integrate it into the app.vue: <template> <div> <vu ...

Unchanging Dive Field

I'm having trouble understanding why this field isn't updating with the correct number. It seems that any value less than 1 is being rounded in the alert() function. I believe all numbers are simply getting rounded down, but I'm unsure of an ...

How can I adjust the appearance of an HTML tag within an Angular component?

I have created an Angular component with the following definition: import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'rdc-dynamic-icon-button', templateUrl: './dynamic-icon-button. ...

Deduct a digit from a variable

My goal is to decrease the value of revlength each time the loop runs. For example, if there are 2 posts by 'A Google user', then subtract 2 from revlength. This is my attempted solution: var revlength = place.reviews.length; if (place.reviews[ ...

Images with fixed positions will be displayed in one div and hidden in all others

I am struggling with integrating multiple images into my webpage in a fixed position. These images should only be visible within their designated divs and scroll along with the content, hiding behind other divs. Unfortunately, I can't seem to locate ...

CSS code for targeting specific screen sizes in the Bootstrap grid system

I'm not an expert in styling, but I often use Bootstrap for small projects. Currently, my main challenge lies within the grid system. With one monitor at a 1920x1080 resolution and another at 1366x768, I find myself wanting to adjust the grid system b ...

Can you help me identify the reason behind a page displaying a temporary horizontal scrollbar?

While browsing the following page in Google Chrome: A horizontal scrollbar appears briefly during page load. It seems that something hidden below the fold is causing this issue, but I haven't been able to identify the exact cause. EDIT:- Watch a v ...

What is the best method for updating audio from a source in Vue.js?

Forgive me if this is a silly question, but I'm still learning the ropes here. I may be going about this in all the wrong ways! I created a backend that learns from a text file and generates sentences along with an audio version of those sentences. I ...

A miniature triangle-shaped bubble crafted with 1px of CSS3 styling

Currently, I am experimenting with CSS3 and creating bubble shapes. However, I have encountered an issue. I am trying to create a triangle with a 1px border, but the result is a thicker triangle than desired. You can view my code on this fiddle : FIDDLE ...

"Passing the v-model property to a child component in Nuxt.js: A step-by-step

I seem to be having trouble passing dynamically modified properties from layouts into the <Nuxt /> component. This is my ~/layouts/default.vue <template> <div> <input v-model="myprop" /> <span>{{myprop}}< ...

Add the search outcome to the input field in vue

Within this section, I have implemented an @click event <h2 @click="action(customer.id)">{{ customer.name }}</h2> My goal is to append the clicked result to the input when any result is clicked. Do you have any ideas on how to achieve this? ...

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

Error: The Vuex store is not defined in the Vue.js component when attempting to access it using

I've recently set up a new vue-cli webpack project with Vuex. I have initialized my Vuex store in store.js like so: import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: {} }); export default store; ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Invoke a function in a different component by utilizing the composition API

Provided below is a code snippet for a header and a body in different components. How can you leverage the composition API to call the continue function of component 2 and pass a parameter when you are within component 1... Code Snippet for Component 2: e ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

Repositioning with Flexbox: shifting the middle element to a new line

I have a flex item that contains three divs. ┌────────────────────────────────────────┐ | WRAPPER | | ┌─────────┬─ ...