Matt
Matt

Reputation: 23

Add class to div, when menu item is clicked

I'm not the best with jQuery, but trying to create a video player where there is a sub menu, and you can click to display different content options. Here's a pic of the frontend (I can do that, at least!) -

image here

So when a user clicks to video or audio, it displays the different div with content in it.

Here's my html markup:

<ul class="vdotb">
    <li><a href="#video"><i class="fa fa-video-camera"></i> Video </a></li>
    <li><a href="#audio"> <i class="fa fa-headphones"></i> Audio</a></li>
    <li class="subs"><a href="#subscribe"><i class="fa fa-microphone"></i> Subscribe to the Podcast</a></li>
</ul>
<div class="tabscontnt">Video Here</div>
<div class="tabscontnt">Audio Here</div>
<div class="tabscontnt">Subscribe info here</div>

And I have the class .tabs-active in my css file displaying as a block. So when the class '.tabs-active' is applied to the 'tabscontnt' div, the content displays.

Here's my failed jQuery...

$('ul.vdotb li a').click(

function(e) {
    e.preventDefault(); // prevent the default action
    e.stopPropagation; // stop the click from bubbling
    $(this).closest('ul').find('.tabs-active').removeClass('tabs-active');
    $(this).parent().addClass('tabs-active');
});

Thanks for any help and your time!

Upvotes: 0

Views: 1676

Answers (1)

user1189882
user1189882

Reputation:

You're applying the class to the <li> element, instead of the corresponding <div> element. Try adding an ID to each <div> that matches the href of the <a> you're clicking on, then use something like this to toggle them:

$('ul.vdotb li a').click(function(e){
  e.preventDefault(); // prevent the default action
  e.stopPropagation; // stop the click from bubbling

  //remove .tabs-active from any active tabs
  $('.tabscontnt.tabs-active').removeClass('tabs-active');
  //add .tabs-active to the corresponding div
  $($(this).attr('href')).addClass('tabs-active');
});

Here's a Fiddle: https://jsfiddle.net/upjyv8a0/

Upvotes: 2

Related Questions