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

Anchor elements and other inline elements not triggering MouseLeave event

Take a look at this CodePen link, particularly in Chrome: https://codepen.io/pkroupoderov/pen/jdRowv Sometimes, the mouseLeave event doesn't trigger when a user quickly moves the mouse over multiple images. This results in some images still having t ...

What is the best way to right-align a label in a vertical MUI Slider in ReactJS?

I am currently working with ReactJS/TS and MUI (Material-UI) to develop a vertical slider that requires the label to be positioned on the right side. By default, MUI places the label on the left for vertical sliders. I have reviewed the API documentation e ...

Issue with Vue Checkbox not functioning properly upon being mounted in Edge browser

Currently, I am developing a Vue page with a checkbox that needs to read a value from a cookie upon mounting. However, I have observed that in the Edge browser, the checkbox does not get set correctly even though the Mounted function is definitely being ca ...

Use PHP to create a new JSON file on the server by submitting a form, then utilize a second form to update

My current goal is to create a json file using a form and then update that file with another form. Both of these processes are handled in the process.php file. I have managed to successfully update the json file if it is named as data.json initially in pro ...

Tips on preventing a nested loop's inner ng-repeat from updating when the array undergoes changes

My current challenge involves working with an array of events, each event has teams participating in it. Although these objects are related, they are not properties of each other. I am attempting to loop through every event and display the teams participa ...

It is impossible for me to enclose a container around a bootstrap 4 navbar

My goal is to wrap a container class around my navbar, but I'm encountering a problem where the toggle button moves to the center in mobile view. <nav class="navbar navbar-toggleable-md navbar-light bg-faded" id="commRollover"> <div cla ...

Having difficulty retrieving/binding the correct Entity Id in JQuery, consistently retrieves the first item Id from the iteration

Within my PartialView, I am looping through a Collection of Entities and displaying them in an Html Table. In one column of this table, there is an element with a font awesome class (fa fa-times-circle). I am setting the "id" property of this to the "I ...

How to make a static div adjust its size in the presence of a neighboring div

I am looking to create a feature where the user can click a button to reveal a new div to the right of an existing one. Check out this Fiddle for reference: http://jsfiddle.net/AV2mZ/. While the functionality works fine when both divs are visible, resizin ...

Choosing the content within a div and inserting it into an email

I have an email sender feature on my website where users can fill out input fields and hit send, resulting in me receiving an email. The text from all the input boxes is included in the email body. Additionally, there are some generated texts in divs with ...

Is it possible to modify the text displayed within a select element?

Currently, I am working on enhancing a react app by making the dropdown options in a select element more informative than what is displayed as the selection. For instance: Selected: A However, when you click on the element for the dropdown it displays: ...

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

The variation in CSS output between Google Chrome on Windows and Ubuntu

My code includes a div tag: <a href="#"><div class="field btn half green" id="register-btn">Register</div></a> Here is the CSS code for the tag: .field { position: absolute; width: 205px; left: 22px; color: #eaeae ...

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

Read PDF on Nuxt site

I am working on a Nuxt app and I need to display a PDF file containing the GDPR policy on a specific page, such as /gdpr. I attempted to place the PDF in the static folder, but accessing it through a URL like /gdpr.pdf did not work. I have been unable to ...

Tips for accessing a local file on a website through HTML - easy steps to follow!

Is it possible to open a local (jpg or pdf) file from a random website that is not under my control? I have tried editing the HTML code of a site in Chrome by replacing existing links with ones linking to my local file, but when I click on them, nothing ha ...

Issue occurs when nested functions prevent the data() variable from updating

As a newcomer to VUE, I may not be using the right terminology so bear with me. I'm attempting to update a variable that is defined in the script tag's "data()" function. The issue arises when trying to change the value of a variable within the ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

Is there a way to refresh a webpage without the need to reload it

Imagine a scenario where a tab on a website triggers the loading of a specific part of the webpage placed within a div. For example, clicking on a tab may trigger the loading of a file named "hive/index.php". Now, if a user selects an option from an auto ...

Guide on transporting PNG files over the boundary

I am working with two specific css commands. code h1 { background: #000000; border-radius: 6px; color: #fff; display: block; font: 40px/60px "Sans", Inconsolata, "Lucida Console", Terminal, "Courier New", Courier; padding: 40px 40px; text-align: center; ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...