0
votes

I am using jQuery to display content on a website based upon the menu item selection. Each menu item has an number attached to it that matches the content div container.

    $(".main-cat").hover(function() {
    $(this).parent().find("div.arrow-right").remove();
    $(this).after('<div class="arrow-down"></div>');
    $(this).addClass('selected');
    $(this).css('cursor', 'pointer');
},
    function() {
    $(this).removeClass('selected');
    $(this).parent().find("div.arrow-down").remove();
});

$("#sidebar div").click(function() {
    $("#real_0").hide();
    $(".content_sub").hide();
    var menuClass = $(this).attr('class');
    menuClassP = menuClass.split(" ");
    $("#real_" + menuClassP[1]).fadeIn('slow');
});

I am trying to add a function that will highlight only the menu item that corresponds to the currently *active* content.

What's the best way to write this? And can my current code be made cleaner?

2
You could use the rel attribute to hold the class that you need. Rather than splitting the string. It would be a bit more clean - brenjt

2 Answers

2
votes

Add

$(this).addClass('selected').siblings().removeClass('selected');

in your click handler, and define a selected class in your CSS that defines the highlight style..

This will add the class selected to the currently clicked element (assuming that is the active content), and remove it from its siblings (the other divs in the sidebar)

0
votes

You can use jquery data attribute by setting something like "data-menuid" for each menu item as an attribute. This way you dont have to split the class name and use it.

<li data-menuid="1">menu</li>

$("#sidebar div").click(function() {
    $("#real_0").hide();
    $(".content_sub").hide();
    $("#real_" + $(this).data("menuid")).fadeIn('slow');
});