21

I tried to write a script which allow me to load certain events when I enter specific url.

My code looks like this:

$(function(){
    var url = window.location.pathname;
    $("url:contains('#Work')").animate({"left": "250"}, "slow");
});

But it doesnt work. Any suggestions? Any help is appreciated.

Robert Greiner
  • 29,049
  • 9
  • 65
  • 85
Eddie
  • 255
  • 1
  • 3
  • 6

2 Answers2

47
$(function() {
    if ( document.location.href.indexOf('#Work') > -1 ) {
        $('#elementID').animate({"left": "250"}, "slow");
    }
});
Ketan Modi
  • 1,780
  • 1
  • 16
  • 28
  • 12
    _Note for passers-by:_ searching a string will return `0` if found at the beginning and `-1` if not found. It works in this case because the fragment will never be at the beginning of the URL, but generally you should search strings with `> -1` or `>= 0`. – Wiseguy Apr 22 '11 at 16:53
11

window.location.href is pulling the URL into a variable, so you can't search for #Work using that method. Try:

var url = window.location.href;

if (url.search("#Work") >= 0) {
    //found it, now do something
} 
Paul
  • 2,186
  • 20
  • 26
  • 5
    _Note for passers-by:_ searching a string will return `0` if found at the beginning and `-1` if not found. It works in this case because the fragment will never be at the beginning of the URL, but generally you should search strings with `> -1` or `>= 0`. – Wiseguy Apr 22 '11 at 16:54