Detect when a child li element is clicked and then toggle the class of its parent div

I have a div container that contains an unordered list tab menu. By clicking on each tab, the menu content changes correspondingly. The functionality is working well, but I want to alter the background image of the container div based on which li is clicked.

Below is my HTML markup:

<div class="menu-container menu-container-starters">
 <ul class="tabs">
  <li class="active" data-trigger-class="menu-container-starters">Starters Content</li>
  <li data-trigger-class="menu-container-mains">Mains Content</li>
  <li data-trigger-class="menu-container-drinks">Drinks Content</li>
  <li data-trigger-class="menu-container-desserts">Desserts Content</li>
 </ul>
</div>

I have assigned background images to the following classes: .menu-container-starters .menu-container-mains .menu-container-drinks .menu-container-desserts

This is my JavaScript code:

$('.tabs li').click(function(){
    $('.menu-container').removeClass('.menu-container-starters .menu-container-mains .menu-container-drinks .menu-container-desserts');
    $('.menu-container').addClass($(this).attr('data-trigger-class'));
});

Answer №1

If you want to see the actual code I created for you, click on this link here.

To improve the code, I added an `id` to the `div` element menu-container and made some modifications to your jquery code.

Hopefully, this will be beneficial for you :)

$('.tabs li').click(function(){
    $('#menu-container').removeAttr('class');
    $(this).closest('#menu-container').addClass($(this).attr('data-trigger-class'));
});
.menu-container-starters{ background: blue; }
.menu-container-desserts{ background: red; }
.menu-container-drinks{ background: yellow; }
.menu-container-mains{ background: orange; }
   

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="menu-container" class="menu-container-starters">
 <ul class="tabs">
  <li class="active" data-trigger-class="menu-container-starters">Starters Content</li>
  <li data-trigger-class="menu-container-mains">Mains Content</li>
  <li data-trigger-class="menu-container-drinks">Drinks Content</li>
  <li data-trigger-class="menu-container-desserts">Desserts Content</li>
 </ul>
</div>

Answer №2

The solution provided is effective, emphasizing the importance of correctly specifying the classes in the removeClass function without including the dot. This ensures that only the desired tab class is added to the div container after each click, avoiding issues with additional classes being appended.

To address the issue, it is recommended to modify the removeClass statement as follows:

$('.menu-container').removeClass('menu-container-starters menu-container-mains menu-container-drinks menu-container-desserts');    

With this adjustment, all existing classes will be removed, leaving only the class associated with the clicked tab intact.

Check out the updated code on JSFiddle 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

Is there a way to simulate a shift+click event on Vue.js elements using the browser console?

My project utilizes the laravel-mix-vue framework for development. As a result, I have implemented several UI functionalities on the Vue side. For example: <template> //... <div @click.prevent="onClick($event)">click element ...

Tips for making a customized drop-down menu using JSON format in AngularJS

This is a unique json dataset I created {0: {'Married Status': {'M', '', 'S'}}, 1: {'COMNCTN_IND': {'', 'OFC', 'RES', 'PGR'}}} I attempted the following: Code: ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Encountered an xHTML error during a jQuery AJAX call that resulted in a "mismatched tag, expected: </br>" message

My issue seems simple on the surface, but I need someone with a deep understanding to help. Picture this straightforward task: loading and parsing external HTML data into an element within the current HTML file. Let's consider the content of the exte ...

Add a combination of strings and a specific date to be stored in a MySQL database

Currently, I am in the process of troubleshooting a script designed to create SEO-friendly URLs. The script is almost functional, but my brain feels nearly fried trying to pinpoint why I keep receiving the incorrect value in MySQL. Here are the values use ...

What is the best way to remove the excess numbers from the return date provided by the react-date-picker?

I need help displaying only the Month and Day with the format "Tue Oct 22 2019". Currently, I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)" when using "react-date-picker". How can I achieve this without having to truncate the te ...

Shift attention to the subsequent division after a correct radio option or text input has been submitted

I need to enhance the user experience on my form. When a user interacts with specific elements like hitting enter in a text input or clicking a radio button, I want to automatically focus on the next "formItem" division. My form structure is organized as ...

Sorting outcomes based on HTML file

Attempting to narrow down results based on certain criteria within a large HTML file. Unsure if my query is attainable, but it never hurts to inquire. Currently immersed in a browser game featuring a vast map measuring 100x100, with each pixel representing ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Tips for preserving session on an Atheros board with C programming to access a website

Currently, I am utilizing the Atheros development board with LSDK-9.2.0_U10.5.13 stack and mips-linux-2.6.31 Linux version. On the board, I have c file, html, js, and css files, without utilizing the cgi library or any scripting language like php. My curr ...

"How can I use node.js to retrieve the number of connections on an HTTP server

I have set up a Node.js HTTP server using the following code: http.createServer(function(req, res) {}).listen(8181); I am interested in finding a straightforward way to monitor the performance of my Node.js HTTP server from within the same process. I wou ...

PyScript <script type="py-editor"> Issue: SharedArrayBuffer cannot be used in an insecure environment

I am currently using PyScript to execute a basic Python script within my HTML file in order to show a pandas DataFrame. However, upon loading the page in the browser and attempting to run the code block by clicking the run button, I encounter an error rela ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

Determine whether the array of an object includes any elements from another array using Lodash

Each product in the array contains a unique structure that includes an ID, name, and materials list. The materials list consists of various materials with their own IDs and names. { id: 1, name: "product 1", materials: [ { id: 1, nam ...

Challenge with Updating React Components When Switching Themes

In my React application, I'm facing a challenge with theme switching. There are two themes available: Theme One and Theme Two. To dynamically load theme components, lazy loading has been implemented based on the selected theme. Each theme has its own ...

when the window is scrolled a certain amount, use jQuery to scroll back in the opposite direction

Using jQuery for Background Image Position: $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 50) { $(".class").addClass("bgposi"); // $(".top").addClass("fixd"); // $(".logo").addClass ...

Problem with the $http module in Angular 1.2

Recently, I started incorporating Angular 1.2.0 into my development application and encountered an issue with a particular function not working as expected: var myItems = angular.model('myItems', []); myItems.controller('itemsController&ap ...

Sending a post request with Ajax in an ASP.NET Webforms application

When attempting to post data to the server using an AJAX call, I encountered an error. var userDetails = {}; userDetails["Name"] = "Saran"; var DTO = { 'userDetails': userDetails }; $.ajax({ type: "POST", contentTyp ...

Refresh sorting in jQuery DataTable

I have encountered a situation where I am trying to accomplish a task that is similar to the one described in this post. Currently, I have a functional jquery dataTable. My goal is to create a function that can reset the sorting to its default state befo ...