Search code examples
javascriptjqueryjquery-pluginsslideranythingslider

How can I change the hashtag names in anythingslider?


I am using anythingslider and if you are familiar with it, you might then know that it has the following function:

hashTags : true,      // Should links change the hashtag in the URL?

Which you can use to make it generate unique URLs for each slide as if they were pages. But the downside is that it generates generic names for the hashtag. (e.g.

http://www.mysite.com/#&panel1-2

My question is, how can you change the names of those hashtags to custom names for each slide?

Right now I am using the following function to make it display each slide title in the navigation bar:

navigationFormatter : function(i, panel){
    return panel.find('h6').text();
}

And all I do is that I add the title in a <h6> element. So, how could I use these titles to also rename the hashtags?


Solution

  • You can turn off the default hash and use the onSlideComplete callback to update the window hash (demo; and full screen demo):

    *note: the h6 also has an id (no spaces allowed) vs the text of the h6 (spaces allowed, and used in the navigation tabs)

    HTML

    <ul id="slider">   
        <li>
            <img src="http://placekitten.com/320/200" alt="" />
            <h6 id="meow">Meow</h6>
        </li>
        <li>
            <img src="http://placehold.it/320x200" alt="" />
            <h6 id="grey">Grey</h6>
        </li>
        <li>
            <img src="http://placebear.com/320/200" alt="" />
            <h6 id="rawr">Rawr</h6>
        </li>
        <li>
            <img src="http://dummyimage.com/320x200/000/fff.jpg" alt="" />
            <h6 id="bnw">Black & White</h6>
        </li>
        <li>
            <img src="http://placedog.com/320/200" alt="" />
            <h6 id="woof">Woof</h6>
        </li> 
    </ul>
    

    Script

    $('#slider').anythingSlider({
    
        // Should links change the hashtag in the URL?
        hashTags: false,
    
        // Details at the top of the file on this use (advanced use)
        navigationFormatter: function(index, panel) {
            return panel.find('h6').text();
        },
    
        // Callback when the plugin finished initializing
        onInitialized: function(e, slider) {
            slider.$items.find('h6').each(function(){
                // add some prefix to the id so setting the hash doesn't
                // make the page jump
                this.id = "tmp_" + this.id;
            });
        },
    
        // Callback when slide completes - no event variable!
        onSlideComplete: function(slider) {
            var hash = '#' + slider.$currentPage.find('h6')[0].id.replace(/tmp_/,'');
            // remove prefix so hash works on page load
            window.location.hash = hash;
        }
    
    });
    

    And here's another demo using the panel ID's instead of the h6 ID's.