0

I'm trying to append a url with an id (just as a test) in my joomla installation using the following code.

jQuery('body').click(function(e) {
    e.preventDefault();
    window.location = jQuery(this).attr('href') + '#test'; 
}); 

Now this works to an extent except it adds the string "undefined" right before "#test".

Example:

www.website.com/articles/undefined#test

Why is "undefined" being added, and is there a way to stop it?

Thanks

3 Answers 3

2

the body tag doesn't have an href attribute. Use

window.location.hash = '#test';

instead.

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

Comments

2

this refers to the body element, which does not have an "href" attribute. So, your call to .attr() returns undefined which is converted to the string "undefined".

If you just want to add "#test" to the url, you don't need to specify a complete URI. Instead you can just specify the relative url, in this case "#test":

location.href = "#test";

If you are trying to append "#test" to a link in your document, you'll need to bind only to links with hrefs:

jQuery("a[href]").click(function(e) {
    e.preventDefault();
    location.href = jQuery(this).attr('href') + '#test'; 
}); 

A couple other notes. You don't need to use jQuery to get the href. It would be simpler and more readable (IMHO) to just do:

location.href = this.href + "#test";

And, rather than preventing default and using javascript to do the navigation, you can just modify the href of the link:

jQuery("a[href]").click(function(e) {
    this.href += "#test";
}); 

Comments

0

That's because the body tag doesn't have a href attribute. This is normally done for links i.e

<a href="some link">Link</a>  

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.