I have an onclick function that I want to add an anchor to the href value. I do not want to change the URL's, because I need the site to still function for people without javascript / for SEO purposes. so here is what I have tried using (amoung other things):
jQuery('a[rel=ajax]').click(function () { jQuery(this).attr('href', '/#' + jQuery('a')); });
An orginal link looks like this:
http://www.mysite.com/PopularTags/
URL re-write should look like this, so that AJAX will work:
http://www.mysite.com/#PopularTags
I was able to get some URL's to work by setting a links name value to the same as the href, but it did not work for links with sub-sections:
http://www.mysite.com/Artist/BandName/
So not really sure. Thanks for the help.
I believe something like
jQuery(function(){
jQuery('a').each(function(){
jQuery(this).attr('href','/#'+jQuery(this).attr('href'));
});
});
will do the job. Read as: At page load, loop through all your links, and replace their href attributes with #{old href}.
It depends how you code your links in the HTML. If you’re linking to http://www.mysite.com/PopularTags/
using this:
<a href="/PopularTags/">Popular Tags</a>
You can simply use this:
$(function() {
$('a[rel=ajax]').each(function() {
var actualHref = $(this).attr('href');
this.href = '/#' + actualHref.substring(1, actualHref.length - 1); // cuts off the first and last characters (‘/’)
});
});
This will result in the following HTML:
<a href="/#PopularTags">Popular Tags</a>
Note that we can set this.href
instead of $(this).attr('href')
, but we still need the latter to get the actual href
attribute. this.href
always holds a full URI, including protocol, domain name, etc — which we don’t want in this example.
I'd suggest to use regular expressions, like
$('a[rel=ajax]').click(function(){
$(this).attr('href', function(){
this.href = this.href.replace(/\/$/, "");
return(this.href.replace(/(.*\/)/, "$1#"));
});
});