user715564
user715564

Reputation: 1690

How to apply jQuery plugin to multiple divs on same page?

I'm working on a jQuery plugin and I need it to work on multiple divs on one page. Basically, I have two menus and when a user clicks on one menu item the background color changes. Right now, the effect is being applied to both menus instead of individually. For example, if I click on item one of menu one the background changes but if I click on item two of menu two, the background of item one menu one is removed while the background of item 2 menu 2 changes.

I need for the menus to be completely separate from each other. Clicking on menu one should not change menu two. Here is how the plugin is set up so far:

(function ($) {
    $.fn.selectBox = function () {
        function get() {
            $('.ms-section-select li').first().addClass('ms-checked');
        }

        function get() {
            $('.ms-section-select li').click(function () {
                $('.ms-section-select li').removeClass('ms-checked');
                $(this).addClass('ms-checked');
            });
        }
        return this.each(get);
    };
})(jQuery);

$('.one').selectBox();
$('.two').selectBox();

Here is a jsfiddle example with all of the code http://jsfiddle.net/977hv/

Upvotes: 0

Views: 112

Answers (2)

Taimour Tanveer
Taimour Tanveer

Reputation: 408

You can try to apply the change on only the siblings of the selected element Is this what you are trying to do? http://jsfiddle.net/977hv/8/

$(this).siblings('.ms-section-select li').removeClass('ms-checked');

To apply it to the first child

    $('.ms-section-select li:first-child').addClass('ms-checked');

Upvotes: 5

gulty
gulty

Reputation: 1076

function selectBox () { 

    $('.ms-section-select li').on('click', function(){
        $(this).siblings().removeClass('ms-checked');
        $(this).addClass('ms-checked');

    })
};

selectBox();

this should do the trick - check: http://jsfiddle.net/977hv/6/

Upvotes: 1

Related Questions