list of current items on the sidebar that are currently being

Hey everyone, I could use some assistance with customizing my sidebar design. I am trying to implement an active state in my sidebar using JavaScript. I attempted to utilize the element.css() method to apply styles when an element is clicked. However, I noticed that once I click on a list item, the hover effect specified in the CSS disappears. This seems to be because the color changes upon clicking and there is no way for it to revert back to its original styling.


var sideNav = $('.sideNav');
$('#dashboard').click(function() {
  sideNav.css({
    'color': '#8c8c8c',
    'background-color': '#373942'
  });
  $('#dashboard').css({
    'color': '#ccc',
    'background-color': '#515461'
  });
});
$('#customers').click(function() {
  sideNav.css({
    'color': '#8c8c8c',
    'background-color': '#373942'
  });
  $('#customers').css({
    'color': '#ccc',
    'background-color': '#515461'
  });
});
$('#items').click(function() {
  sideNav.css({
    'color': '#8c8c8c',
    'background-color': '#373942'
  });

  $('#items').css({
    'color': '#ccc',
    'background-color': '#515461'
  });
});

.sidebar {
  background-color: #373942;
  margin-left: -15px;
  position: fixed;
  width: 230px;
}

.sidebar ul {
  padding-top: 30px;
}

.sidebar li {
  color: #8c8c8c;
  text-decoration: none; 
  list-style-type: none;
  line-height: 45px;
  cursor: pointer;
  /*background-color: red;*/
  margin-bottom: 1px;
  /*margin-left: 20px;*/
  padding-left: 40px;
  font-size: 15pt;
}

.sidebar li:hover {
  background-color: #515461;
  color: #ccc;
  border-left: 4px solid #8c8c8c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <ul>
    <li id="dashboard" class="sideNav">Dashboard</li>
    <li id="customers" class="sideNav">Customers</li>
    <li id="items" class="sideNav">Items</li>
  </ul>
</div>

Answer №1

To enhance user experience, it's recommended to avoid inline styles for indicating active buttons upon clicking. Instead, define a specific class to signify an active button and utilize methods like toggleClass or a combination of addClass and removeClass to achieve this functionality.

For a practical demonstration, check out this code snippet on JSFiddle: https://jsfiddle.net/hwwy8yhL/2/

Cascading Style Sheets (CSS)

.sidebar {
  background-color: #373942;
  margin-left: -15px;
  position: fixed;
  width: 230px;
}

.sidebar ul {
  padding-top: 30px;
}

.sidebar li {
  color: #8c8c8c;
  text-decoration: none;
  list-style-type: none;
  line-height: 45px;
  cursor: pointer;
  /*background-color: red;*/
  margin-bottom: 1px;
  /*margin-left: 20px;*/
  padding-left: 40px;
  font-size: 15pt;
}

.sidebar li:hover {
  background-color: #515461;
  color: #ccc;
  border-left: 4px solid #8c8c8c;
}

.sidebar li.active
{
  color: #ccc;
  background-color: #515461
}

JavaScript (JS)

var sideNav = $('.sideNav');
$('#dashboard').click(function() {
  sideNav.removeClass('active');
  $('#dashboard').addClass('active');
});
$('#customers').click(function() {
  sideNav.removeClass('active');
  $('#customers').addClass('active');
});
$('#items').click(function() {
  sideNav.removeClass('active');
  $('#items').addClass('active');
});

Answer №2

Here is a straightforward solution using the jQuery function and CSS below:

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <ul>
    <li id="dashboard" class="sideNav">Dashboard</li>
    <li id="customers" class="sideNav">Customers</li>
    <li id="items" class="sideNav">Items</li>
  </ul>
</div>

Jquery

$('.sideNav').click(function() {
  $('.sideNav').removeClass('active');
  $(this).addClass('active');
});

CSS

.sidebar {
  background-color: #373942;
  margin-left: -15px;
  position: fixed;
  width: 230px;
}
.sidebar ul {
  padding-top: 30px;
}

.sidebar li {
  color: #8c8c8c;
  text-decoration: none;
  list-style-type: none;
  line-height: 45px;
  cursor: pointer;
  margin-bottom: 1px;
  padding-left: 40px;
  font-size: 15pt;
}
.sidebar li:hover{
  border-left: 4px solid #8c8c8c;   
}
.sidebar li:hover, .sidebar li.active{
  background-color: #515461;
  color: #ccc;

}

For the full snippet in CodePen, click here.

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

Angular- Product Details

I'm currently expanding my knowledge of angular (utilizing the ionic framework with phone gap included) and I'm working on developing a single application that displays a list of data. When a user clicks on an item in the list, I want to show the ...

Online platform offering a versatile calendar feature powered by jQuery

I have a website where I used a jQuery calendar on many pages. The calendar worked perfectly for me locally, but when I uploaded the website to my hosting.com server, the jQuery calendar stopped working. However, other jQuery code is still functioning corr ...

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

Would you like to learn how to set an auto-play video as the background in a webpage section, similar to the one found on http://www8.hp.com/in/en/home.html?

I was browsing the HP-India website and noticed they have a cool autoplay video in the background of a section below the header. I would love to recreate something similar on my own website. Any tips on how to achieve this? ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Right-align each item when selecting none

Is there a way to change the style of just one of the elements select or option, without affecting the style of both? I attempted to align the select element to the right, while leaving the option elements aligned to the left. However, this did not work a ...

The function `createUser` is currently not functioning properly on Firebase/Auth with Next.js

I am currently working on implementing email and password authentication using Firebase Auth with Next.js. This time, I want to utilize a dedicated UID for authentication purposes. In order to achieve this, I believe it would be better to use the createU ...

Optimal viewing experience with organized sections in full-screen layouts

There are numerous ways to make a div cover the entire screen with a full-screen image in the background. However, most of them involve using min-height:100% and background-size:cover properties. This can sometimes cause other sections like the footer or h ...

Problems with Vuex getter reactivity when used in conjunction with Vue router

I've encountered an issue with my Vuex getter that fetches data for the current route and displays it in a Vuetify v-data-table. Everything works perfectly fine when the component is initially created. However, when I add a new entry to the data array ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

Trouble with exporting and importing an Express application

Starting with a simple Express example of 'Hello World', I am looking to refactor the code into separate files for configuration and routing. var express = require('express'); var app = express(); app.get('/', function (req, ...

Cleanse the email using express-validator, but only if it is recognized as an email format; otherwise, disregard

Currently, I am developing an API that requires users to input their username and password for authentication purposes (login functionality). Users have the option to enter their email, username, or mobile number. To ensure consistency, I need to normalize ...

Codeigniter AJAX search feature encountering a glitch

I am currently working on creating an Ajax search feature with suggested results in a dropdown menu. However, whenever I type something in, I keep encountering the error "Error while request.." and the console shows a connection refusal to the post URL in ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

Is there a way to make a sass file universally accessible without having to import it into every file and causing an increase in bundle size?

Question How can I efficiently import variables.scss globally without the need to duplicate them in every file and reference them in my build instead of importing? Setup I am using Vue2 with laravel-mix, where I have imported index.scss in my main.js ...

Exploring Jasmine and AngularJS: Testing a factory function in the context of dependency injection

Looking to create a unit test for a simple factory that calculates the sum of two numbers. (function () { "use strict"; angular .module("math") .factory("addservice", [addTwoNumbers]); function addTwoNumbers(a, b) { ...

Issues with sending data from JavaScript to ActionScript in Internet Explorer

My attempt to transfer a string from an HTML page (using JavaScript) to a SWF file (ActionScript 2) was not successful. After some research on Google, I came across this page. However, the example code (version 1) mentioned on the page did not work in In ...