curly_brackets
curly_brackets

Reputation: 5598

Get index of anchor/hash

I'm killing my self here.

When I type in index.html#about (or favorite it and open it) i want to get the index() of this, and insert it in the below script as "slideNumber".

Markup

<div id="slideshow">
    <div id="frontpage">
    <div id="About">
    <div id="Contact">
</div>

jQuery

$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    $('.slideshow').cycle(slideNumber); //Slideshow-number
});

"#about" would be 2 and "#contact" would be 3 and so on.

How do I do this??

Upvotes: 0

Views: 1494

Answers (3)

Alex
Alex

Reputation: 344

Give this a try

var slideNumber = $("div#" + window.location.hash.slice(1)).prevAll().length

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40543

slides = {frontpage: 1, about: 2, contact: 3};
$('.slideshow').cycle(slides[hash]);

To make it dynamic you could use something like this, I guess:

$('#slideshow>div').each(function(i) {
  if(this.id == hash) {
    $('.slideshow').cycle(i);
  }
}

or

$('.slideshow').cycle($('#slideshow>div').index(hash) + 1);

Upvotes: 0

kafuchau
kafuchau

Reputation: 5593

Something simple like this should work on the page load:

if(window.location.hash != undefined) {
  var slideNumber = $(window.location.hash).index() + 1;
}

If you're navigating through the page, you can do your bind and do the index() call inside so that when the hash changes, it'll update:

$(window).bind('hashchange', function () { //detect hash change
    var slideNumber = $(window.location.hash).index(); //slideNumber
    $('.slideshow').cycle(slideNumber); //Slideshow-number
});

Upvotes: 1

Related Questions