Applying the .active class to a button which reveals the corresponding div

I've been working on a menu that functions to open and hide divs within a single page.

My objective is to have the (.active) class applied to the currently selected menu item only when its connected div is open. When the div is closed or another menu item is selected, the class should either disappear or be transferred to the new menu item.

I attempted to use

$(".your_selector li").addClass("active");
but this code simply marks all menu items as active, which is not the desired outcome.

How would you approach solving this problem? Here is the fiddle http://jsfiddle.net/4DGUV/3/

Thank you in advance

Answer №1

Revise your code to use this script instead: http://jsfiddle.net/4DGUV/7/

$('document').ready(function () {
  $('button').click(function () {      //<----click the buttons
      $('button').removeClass('active'); //<-----remove the class from the button
      $(this).addClass('active'); //<---add the class to currently clicked button
      var $div = $('#' + $(this).data('href'));
      $('.demo').not($div).hide();
      $div.slideToggle();
   });
});

Alternatively, you can try a more optimized approach using this script: http://jsfiddle.net/4DGUV/8/

$('document').ready(function () {
  $('.menu li').click(function () {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var $div = $('#' + $(this).data('href'));
    $('.demo').not($div).hide();
    $div.slideToggle();
  });
});

Make sure your HTML structure follows this format:

<div class="menu">
  <ul>
    <li> <a href='#' id="show2" data-href="vission1">news</a>

    </li>
    <li> <a href='#' id="show3" data-href="mteam">team</a>

    </li>
    <li> <a href='#' id="show1" data-href="mission1">download</a>

    </li>
  </ul>
</div>

Answer №2

Make sure to include the following code snippet within a click event attached to an li element.

For instance:

$(".your_selector li").click(function(){
    $(this).addClass('active');
});

The reason this is necessary is because you are applying the addClass function to all li tags, so in order to target only the specific clicked li, you must specify that using jQuery.

Answer №3

Here is a helpful snippet to utilize:

$(".your_selector li").on('click', function(){
    $(this).toggleClass('active');
});

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

What is the reason for the automatic loading of coffee files in app/assets/javascripts across all files?

I have a question about organizing my Javascript files in my app. I have multiple files in the app/assets/javascripts folder, and for testing, I have written some code in a file named test.coffee: $ -> $(document).ready -> alert("Hey"); When ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

restructure the HTML based on a jQuery condition

Using jQuery to Refresh HTML Content function(data) { if(data === "importtrue") { $('#rebuildme').//function like .html } else { $('#rebu ...

Is there a way to change the color of a checkbox (both the box and font) in the disabled state using material ui

When using Material UI v4.9.12, it is possible to create a customized checkbox with a specific color that remains fixed: const GreenCheckbox = withStyles({ root: { color: green[400], '&$checked': { color: green[600], }, ...

Position a div at the bottom of another div using Bootstrap

I'm facing an issue with trying to position an inner div at the bottom of an outer div using bootstrap classes. I have attempted various methods in both bootstrap and regular CSS, such as vertical-align: bottom; and setting position to absolute, but n ...

Troubles with caching on Amazon S3

Just starting out in web development and I'm working on updating HTML and CSS files stored on Amazon S3. Our website's backend is hosted on Heroku, while the front-end is on Amazon S3. Whenever I make changes to a CSS file, I can immediately see ...

In JavaScript, when you update the property of a nested object within an array, the changes will also be applied to the same property for

Encountered an interesting issue in my code where updating a single property of a nested object within an array of objects results in all similar objects having the same property updated. Snippet of the Code: let financials = { qr: { controlData: [ ...

Using CSS or Bootstrap, align the image to the right side of the content

Struggling to align an image to the right of the content area, inspired by this Dribble shot. Check out the inspiration here This is what I've come up with so far: Link to my progress on CodePen .content { position: relative; } .bg-image { posi ...

Modify the text in a paragraph by clicking on a link using JQuery and HTML

I'm attempting to implement a straightforward action, but I'm facing some challenges. My navigation bar consists of a few links followed by a text section. What I aim for is that when I click on a link, the paragraph of text should change to refl ...

Understanding the process of extracting map data from JSON files

I am currently working with Spring 3 and JQuery. My goal is to retrieve a Map containing element IDs and their values from my Spring Controller, and then use this data to update the View. Below is a snippet of the Controller code: @RequestMapping(value= ...

What is the reason for the delay in the firing of this document.ready event

Similar Question: Understanding window.onload vs document.ready in jQuery I seem to be encountering a problem: I have an image on my webpage that is relatively small. I also have a JavaScript function that dynamically sets the height of the left sideb ...

Mastering TailwindCSS: Enhancing your design with group-hover utilities for top, bottom, right, and left

In a div, there is an <img> tag and a <button> tag. I used group in the className of the div and group-hover:opacity-0 in the img tag, and it worked correctly. However, when I applied group-hover:top-1/2 to the <button> tag, it did not wo ...

Add the data object list to the serialized format

I am looking to map a list of data objects with serialized form data in my backend, which is .Net. I have a Model class set up to map the parameters. Below is the jQuery object I am currently using: var MultiAssignGarageCampaign = []; var obj = {}; ...

What is the process for closing the lightbox?

My code is supposed to display a lightbox as soon as the page loads, similar to a popup window. However, there seems to be an issue with closing the lightbox when clicking on the 'x' button at the corner of the box. Unfortunately, the current cod ...

Error encountered when trying to access JSON data using jQuery due to a formatting issue

I encountered an issue with accessing and storing the contents of a JSON file into an array. Despite everything seeming to function correctly, I am receiving an error in the console when using Firefox. Not Well Formed. The error points to my JSON file. H ...

customized multiselect dropdown with grouping options using Bootstrap

My dropdown menu looks like this: <select class="selectpicker" multiple> <optgroup label="option 1"> <option value="1">1</option> <option value="2">2</option& ...

Incorporate an MP3 audio track into an image

Greetings, I have an image and I am interested in embedding the associated MP3 file directly onto the image instead of having it displayed separately below. Is this achievable? Thank you Best regards, Gary <!doctype html> <html> <head&g ...

Upon the initial visit to the website, unregistered users will be prompted with a dialog box in Laravel asking them to confirm that they are over 18 years old

In my Laravel 5.2 project, I'm faced with a challenge - how to display a confirmation dialog for users who visit the website for the first time and are not registered, asking them to confirm that they are above 18 years old. To tackle this issue, I be ...

The data variable in Vue.js does not show up in the view even when it is populated through an AJAX request

I am facing an issue with my code, where the 'tarefas' variable is not appearing in my v-for loop. I have verified that the response from the server is correct and the data is being received. Interestingly, when I add new data in the input field, ...

It is not possible to highlight the text that appears in the title of the tooltip in React MUI

Within my react application, there is a component that utilizes the code snippet below: <FormControlLabel labelPlacement="top" control={ comp?.manualInput ? ( <TextField name="price" type= ...