Jon
Jon

Reputation: 3

Add body #id based on url

Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.

- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...

My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?

- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2

Here's the JS code I'm using (found online)

$(document).ready(function() {
    var pathname = window.location.pathname; 
    var getLast = pathname.match(/.*\/(.*)$/)[1];
    var truePath = getLast.replace(".html",""); 
            if(truePath === "") { 
                    $("body").attr("id","index");
            }
            else { 
                    $("body").attr("id",truePath);
            }       
    }); 

Thanks in advance!

edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.

http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.

Upvotes: 0

Views: 2142

Answers (5)

T. Stone
T. Stone

Reputation: 19495

Using the javascript split function might be of help here. For example (untested, but the general idea):

var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');

$('body').id = segments[0];

Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...

var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');

for (var i = 0; i < segments.length; i++) {
    $('body').addClass(segments[i]);
}

EDIT:

Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...

var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');

If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...

url = url.replace(/\?.+$/,'');

Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..

var $body = $('body');
for ( ... ) {
   $body.addClass( ...
}

Upvotes: 1

jcadcell
jcadcell

Reputation: 811

If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:

var getLast = pathname.match(/\/(page\d+)\//)[1];

The above would match "page" followed by a number of digits (omitting the 'html' ending too).

Upvotes: 0

Guffa
Guffa

Reputation: 700372

You want to get the first part of the path instead of the last:

var getFirst = pathname.match(/^\/([^\/]*)/)[1];

Upvotes: 0

cheeken
cheeken

Reputation: 34655

Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.

$(document).ready(function() {
    $("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}

Upvotes: 0

tjarratt
tjarratt

Reputation: 1690

Your regex is only going to select the last part of the url.

var getLast = pathname.match(/./(.)$/)[1];

You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.

If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.

edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.

What are you actually trying to do?

Upvotes: 0

Related Questions