Search code examples
jquerycyclejquery-cycle

jQuery Cycle - creating pager links from link inside div


I'm putting together a nav for the front page of a site and I'm trying to get Cycle to use a custom pager link from the link contained inside a div.

Here's my current code:

$('#nav-cycle').before('<ul id="nav">').cycle({ 
    fx:     'turnLeft', 
    speed:  'fast', 
    timeout: 9001,
    pagerEvent: 'click',
    pauseOnPagerHover: 1,
    pager:  '#frontpage-nav', 
    allowPagerClickBubble: true, 
    pagerAnchorBuilder: function(idx, slide) { 
         return '<li><a href="#">' + slide.title + '</a></li>';
    } 
});

I need it to use the href from the link that is contained in each slide's div as the pager link. I found a question that seemed similar to this but without needing to get the link inside.

HTML as requested, with all the PHP stripped:

<div id="frontpage-nav"></div>

<div id="nav-cycle">
<div class="nav-cycle-item" title="(page title)">
<p class="nav-item-description">(page description text)</p>
<span class="page_link"><a href="(link)">(page title)</a></span>
</div>

Solution

  • In the pagerAnchorBuilder function, "slide" refers to the current <div class="nav-cycle-item">. To get the href of each <a> tag within each div, just use a jQuery selector to find the child <a> and get it's href value:

    $('#nav-cycle').before('<ul id="nav">').cycle({ 
        fx:     'turnLeft', 
        speed:  'fast', 
        timeout: 9001,
        pagerEvent: 'click',
        pauseOnPagerHover: 1,
        pager:  '#frontpage-nav', 
        allowPagerClickBubble: true, 
        pagerAnchorBuilder: function(idx, slide) { 
            var href = $(slide).children('span').children('a').attr('href');
            return '<li><a href="' + href + '">' + slide.title + '</a></li>';
        } 
    });
    

    BTW, I'm assuming you're missing a closing div in your HTML above.