+ Reply to Thread
Results 1 to 2 of 2

Thread: jQuery issue

  1. #1

    jQuery issue

    I have the UL list and the code which selects the all parents of the selected LI element , I want to clear the selection when I select the other LI element. To do so, I've created that code:
    Code:
        $('#nav li').click(function () {
            //clear the previous selection
            $.each(myArray, function (i, v) {
                console.log('loop: ' + v);
                $('#nav li a[href="' + v + '"]').css('background-color', 'Green');
            });
    
            myArray.lenght = 0;
    
            //add the new selection
            $(this).children('a').each(function (item) {
                myArray.push($(this).attr('href'));
                console.log('adding: ' + $(this).attr('href'));
                $(this).css('background-color', 'Red');
            });
        });
    but, that code generates that output if I select the 1st path.

    Code:
    adding: #/1210
    
    loop: #/1210
    
    adding: #/1209
    
    loop: #/1210
    
    loop: #/1209
    
    adding: #/1208
    If I select the e.g. 2nd path, the output is:

    Code:
    loop: #/1210
    
    loop: #/1209
    
    loop: #/1208
    
    adding: #/1188
    
    loop: #/1210
    
    loop: #/1209
    
    loop: #/1208
    
    loop: #/1188
    
    adding: #/1187
    I think the output should be (the 2nd path selection)

    Code:
    loop: #/1210
    
    loop: #/1209
    
    loop: #/1208
    
    adding: #/1188
    
    adding: #/1187
    Can someone explain this for me ?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    40
    The click event originates from an a element. So catch it first before it bubbles to the first li, and make all the as default.
    Code:
    $('#nav a').click(function() {
        $('#nav a').css('background-color', 'green'); 
    });
    $('#nav li').click(function () {
        $(this).children('a').css('background-color', 'red'); 
    });
    But it's much better to do this whole thing with CSS classes:
    Code:
    $('#nav a').click(function() {
        $('#nav a.current').removeClass('current'); 
    });
    $('#nav li').click(function () {
        $(this).children('a').addClass('current'); 
    });
    Also add this in CSS:
    Code:
    #nav a { background-color: green; }
    #nav a.current { background-color: red }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts