Search code examples
jqueryvariablesattr

Using data attributes for jquery to relate two elements


One of the first things I learned in jQuery is the Click() function and how great it is at getting one element to effect another. However, what should I do when I have an array of items (all over my document) that I want to have effect a whole 'nother array of elements once again scatted across my document?

In my strange mind, I am thinking to use data attributes. You can see a VERY simplified version here: http://jsfiddle.net/Qnzpg/

First off, my example on jsfiddle has many a better solutions, I am aware. However, the real application is a bit more complex and requires this method.

I am trying to pass the value of my data attribute as a variable, and have the element that shares that variable be effected (in my example, by having it add a class):

$("#menu [data-cell]").click(function (e){
    e.preventDefault;

    //make the data value a variable
    var $cell = $(this).data();

    //find the other element with the same data value and add the class named "open"
    $('#pages [data-cell='$cell']').addClass('open');
});

I've been fiddling with my jQuery for a very long time now and feel it's best to call in the experts.

What here am I doing wrong?


Solution

  • Here you go:

    $('#menu li a').each(function() {
        $(this).click(function() {
            var attr = $(this).parents('li').attr('data-cell');
            $('#pages div').each(function() {
                $(this).removeClass('open');
                if($(this).attr('data-cell') == attr) {
                    $(this).addClass('open');
                }
            });
        });
    });
    

    Fiddle: http://jsfiddle.net/Qnzpg/7/