0

I have all my javascript code for i project in a single minified library. There are some functions that run only for specific page urls, but when a link that does not have its href attribute and instead has an element id its href attribute is clicked, and the page is refreshed, the function does not run. Any idea what the problem is? For example; it work when the url is http://localhost/pheedbak/users/home but when the url changes to http://localhost/pheedbak/users/home#directed-pheeds, the function doesn't run

The code is something like this

url = "http://localhost/pheedbak/users/home";

    if(window.location.href == url)
    { 
      pheeds.LoadLatestPheeds();
    }
3
  • 1
    Not sure what you mean. Example? Commented Oct 29, 2011 at 14:28
  • They mean the script relies on link elements with normal URLs and fails for anchor links. Commented Oct 29, 2011 at 14:32
  • How do you click on a href attribute? Commented Oct 29, 2011 at 14:39

3 Answers 3

3

This should work -- only look at the stuff before #

 if(window.location.href.split("#")[0] == url)

or

 if(window.location.href.split("#",1)[0] == url)

nb. not tested -- might contain typos/bugs.

Sign up to request clarification or add additional context in comments.

Comments

2

You can try this, this will match even if there are other querystrings or hash ids:

if(window.location.href.indexOf(url) > -1)

1 Comment

Although this will probably work without problems for the example given, it's not best practice to use this type of method for matching the url. For example, this would also match a query with "/path/to/whatever?url=locahost/pheedbak/users/home", and if you are using relative paths the matching is off all together. Better to be as precise as possible. Of course as in his example this is very unlikely to actually happen.. but that's what best practice is all about. Preventing Murphy's Law.
2

You'll need to strip out the important part. Eg

var url = 'pheedbak/users/home';

if(window.location.href.replace(/.*?\/\/.*?\/(.*?)(?:\#|\?).*/,'$1') == url)
{ 
  pheeds.LoadLatestPheeds();
}

This will also work with url's that contain GET variables (eg. /users/home?id=2) and works regardless of domain or protocol.

Domain & Protocol dependent version:

var url = 'http://localhost/pheedbak/users/home';

if(window.location.href.replace(/(.*?)(?:\#|\?).*/,'$1') == url)
{ 
  pheeds.LoadLatestPheeds();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.