views:

20

answers:

4

I am currently working on a site in a staging environment located at www.example.com/staging. All of the links for the site have been set relatively (ex: /about/). I am trying to write some simple jQuery to add "/staging" to every link on the pages, so I don't have to change all the links for the week or so it is in the staging environment. I know the HTML tag is an option, but because the links are being added dynamically with ExpressionEngine that doesn't seem to work. I think the jQuery should be fairly simple. Here is what I have, but something isn't quite right:

$(function() {
  var href = $('a').attr('href');
  $(href).prepend('/staging');
});

Thanks in advance for the help.

+1  A: 
$(function() {
  $('a').each(function() {
    $(this).attr('href', '/staging' + $(this).attr('href'));
  });
});

$(href) doesn't find anything because it's just the value of the attribute.

EDITED: cuz I was retarded >_<

shoebox639
This will change all links to be the same as the first link on the page (with `staging` prepended).
Drackir
Wow I gotta lay off the crack... There fixed. Thanks for the catch.
shoebox639
+1  A: 

The URL examples you have posted (/about/ and /staging) are not relative; they are rooted. These paths will not do what you seem to be trying to do here.

Relative URLs never start with the slash; they start with a path part (a name, or dots). Having the slash at the beginning forces the browser to look from the root of the host for the link, just like having the slash at the beginning of a path name in a file system does.

Andrew Barber
+3  A: 

Try this:

$(function() {
  $('a').each(function() {
    var href = $(this).attr('href');
    $(this).attr('href', '/staging' + href);
  });
});
Drackir
Perfect! This one worked great. @shoebox639's answer seemed to change all of the hrefs to /staging/staging. Thanks for the help.
Andrew
You're welcome! :)
Drackir
A: 

An alternative to jQuery is to use the <base> tag.

Adding <base href="http://www.example.com/staging/" /> inside your <head> tag will make all of your /about/ (etc) links work the way that you want.

Actually, I don't think this will work for you. It would work if you had URLs like about/ which are real relative links. /about/ isn't a relative link. I'll leave this answer here in case someone find this later through a google search and needs a solution for relative links.

If your URLs were of the less common form ./about/ then this solution would work. Browsers would treat (and display) the URL ./about/ as http://www.example.com/about/ without a <base> tag or as http://www.example.com/staging/about/ if you set a <base> tag in the way above.

Blair McMillan