Search code examples
jqueryclonehyperlink

JQuery erratic behavior of cloned links


I have links to pages of data displayed at the top of my page. I've cloned this to the bottom of the page as well. The problem lies in attempting to remove the href attribute of the active page. This works for the top row of links, but not for the bottom.

<div class="pages"></div>

<div id="workspace"><br/></div>

<div id="pagesclone"></div>

jquery:

//Generate page number links
for (x = 1; x < 6; x++) {
    $('.pages').append(' <a href="#" class="links">' + x + '</a> ');    
}

page = 1;

//Function for link clicks
$('.links').click(function() {
    //"You clicked .."
   current = $(this).html();
   $('#workspace').html('You clicked ' + current);

    //shifting the active page    
   $('.links').slice(page - 1, page).attr('href', '#'); //activate preceeding link
   page = $(this).html(); //reset page number to the link clicked
   $('.links').slice(page - 1, page).removeAttr('href'); //remove href attribute
});


//Clone the top row of links to the bottom
$('.pages').clone(true, true).appendTo('#pagesclone');

Everything looks correct to me. How could I make the cloned links on the lower page also have the href attribute remove when clicked, and vice-versa?

Jsfiddle: http://jsfiddle.net/JshnC/10/


Solution

  • The main problem is that your page index only points to the elements of the first row. If you add half the length of $(".links") you get the index of the element of the second row, and you can make it work.

    There is a working (but ugly) version taking this approach at http://jsfiddle.net/dLKfA/

    You can make your code much nicer if you introduce some more classes:

    When generating:

    $('.pages').append(' <a href="#" class="links link-' + x + '">' + x + '</a> ');    
    

    Then when updating:

    $('.links.link-' + page).attr('href', '#'); //activate preceeding link
    page = $(this).html(); //set page number to the link clicked
    $('.links.link-' + page).removeAttr('href'); //remove href attribute 
    

    But also, what @elclanrs said about globals. They are very likely to bite you at some point.