javascriptjqueryhtmlcssjquery-ui-tabs

remove/add class to parent div when child li is clicked


I have a div container that houses a unordered list tab menu. When I click each tab the menu content changes accordingly. It currently works nicely however I would like to change the background image of the container div that houses the ul content depending on which li is clicked.

Here is my 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 the following classes with background images assigned: .menu-container-starters .menu-container-mains .menu-container-drinks .menu-container-desserts

My JS is:

$('.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'));
});

Solution

  • Here's the link of the actual code that I have created for you https://jsfiddle.net/beljems/b3v8g3by/.

    I just added id to the div element menu-container and modified your jquery code.

    Hope this will help 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>