How to append another directory link to <a> in HTML - javascript

I am looking to create a simple following link to append to the current location.
Straight to examples
www.domain.com/link/address
link required
www.domain.com/link/address/newbit
I have tried the following so far:
<a href=#/newdir> //fail
result: www.domain.com/link/address#/newdir
<a href=/newdir> //fail
result: www.domain.com/newdir
<a href=./newdir> // fail
result: www.domain.com/link/newdir
So unless I have to use the trailing forward slash on the previous link, it appears this is actually not that easy.
Any suggestions welcome.
Thanks
P.S. I would like to do this without jQuery or Javascript if possible

That won't be possible if you do not prepend your base path with JavaScript or when the links are rendered server-side.
Prefixing the links with a / means look from the root, which is "http://www.domain.com".
EDIT : Check the base element on W3Schools. It will add a base path for all relatives URLs in the document.
EDIT 2 : If you are already on /adress/, #Adeneo's suggestion will obviously work.

append using jquery here is a sample code...
url
$(function(){
var current_location='www.domain.com/link/address';
$("#url").attr('href',current_location+"/newbit");
});

If www.domain.com/link/address is the page that you are already on, then
newdir
would be enough, resulting in www.domain.com/link/address/newdir address.
If not, you should use JS.

I think you can do this in a clever way , you just have to add a jQuery function that gets the href value and redirect where you want after processing. like this
$("a").click( function () {
var href = $(this).attr("href");
// the variabel href is everything inside the attribut href
location.href = "http://domain/" + href ;
});

Related

Adding to/editing the URL bar of a webpage without deleting what's already there.

I need to add some text to a URL bar without deleting what's already there(as I've mentioned in the title). Basically, I have eight or so hashes(/one/, /two/, /three/, etc).
I have to add these to the URL bar without deleting the previous hashes that are already in there. For example, I could have a button that adds "/two/" to the URL, but what if "/one/" is already there? I need it to make it so that it just adds the new hash after the one one, like this - "/one/two/three/".
I've tried using
Hide "one"<br/>
and
Hide "two"<br/>,
but unfortunately when I use the second one after the first, it just replaces "/one/" with "/two/".
Any suggestions would be great. Let me know if I need to provide some more context, I'm not quite sure what's relevant to this question in my code.
Thanks in advance, guys!
You just need to use a function
<a onclick="addHash('/one/');">One</a>
<a onclick="addHash('/two/');">Two</a>
function addHash( hash ) {
window.location.hash = window.location.hash + hash;
}
You will probably need to do some checking in the addHash function to see if it exists already, but thats a good place to start.
Maybe a little more description on what you are trying to achieve here?
Are you just trying appearance of the URL, or are you trying to navigate to pages with these arguments?
I'm sure PHP would solve this with the following but I'm not sure why you would use it.
One
Two
If you're using jQuery you could do:
One
Two
<script>
$(function(){
$('.addToUrl').click(function(){
var href = $(this).attr('href');
window.location.href = window.location.pathname + href;
});
});
</script>

jquery - significance of .hash in this function

I borrowed someone's jquery function and adapted it for my own use, but I do not understand exactly how it works. Specifically the line var content = this.hash.replace('/', '');
Could someone please explain .hash in this context?
The full jsFiddle is here: http://jsfiddle.net/bsapaka/KjcnL/3/
$(document).ready(function () {
var tabs = $(".tabs-group li a");
tabs.click(function () {
var content = this.hash.replace('/', '');
tabs.removeClass("active");
$(this).addClass("active");
$("#panel > div").hide();
$(content).fadeIn(700);
$(this).delay( 800 );
});
});
That gets the part of the href after (and including) the #.
An <a> element has several such properties, like:
hash
host
href
hostname
pathname
protocol
search
In that context, they're using the hash as an id to fetch another element. Because the # is present, it's a valid id selector.
If you look at the way the following anchor tag is set up:
<li>Health & Fitness
The hash value is the part of the href attribute after and including the hashtag: #
In this case, the code stores the ID of the element to be shown when the anchor tag is clicked in the hash, then a few lines below, the value of the hash is used as a JQuery selector to show the specified element (note that the hashtag is also the ID selector in JQuery):
var content = this.hash.replace('/', ''); // returns '#hnf' for the <a> tag above
[...]
$(content).fadeIn(700); // '#hnf' is the ID of an image on your page to display
Beware though, because using hash navigation in this way may cause unexpected results when a user tries to use the back button. Hashtag navigation is usually used to create entries in a browser's history upon displaying new data without actually navigating to a different HTML page. You should research hash navigation further for ways to prevent some of the pitfalls. The following SO post may be a good place to start if you find the back button behavior is undesired:
How to make the browser back button disregard hash tags?
I believe that hash is found on elements that contain an href attribute or property
the bolded text is the hash.
http://www.example.com/page.html#stuff

jQuery if url hash, click event/activate javascript

So from the home page, i have a link that goes to a products listing page.
The product page has expand/collapse divs.
I need the appropriate div to expand depending on what the url# is.
So the link on the homepage is
healthy snacks
when i click the link above, i am trying to activate this, on the product page:
Healthy Snacks
I've tried some of the other codes that i found that trigger click by checking for hash tag and none of them were working properly, i think it's because of the ReverseDisplay js.
Please any insight would help.
thanks
You can make the following changes in the document ready function of your product page:
Simple fix: Since the jQuery id-selector is #elementId, you can simply use the window.location.hash value as your id selector, and use it to target the desired element.
if ( window.location.hash ) {
$(window.location.hash).click(); //clicks on element specified by hash
}
Better: In addition to the above, take the js out of your markup.
$('#healthysnacks').click(function(e) {
e.preventDefault();
ReverseDisplay('products4');
});
Then, after doing this, use the $(window.location.hash).click() code from above.
Also, change your link to:
Healthy Snacks
You can use the hash property of the Location object, try the following:
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click')
})
As you are using jQuery instead of using javascript: protocol, you can use the jQuery click method:
$('#healthysnacks').click(function() {
// do something here
})
The answers suggested here are valid, but...
Be extremely careful when using the window.location.hash as it is in a jQuery selector because this could lead to a XSS vulnerability. $() can also create an HTML element and with a carefully constructed hash value, someone could execute arbitrary JavaScript code.
For example
http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>
If my-websites.com/about page uses the window.location.hash inside a jQuery selector, that onerror code would end up getting executed.

Use Javascript to get url of the page and use it in a link

I have looked and looked for an answer to this question. So I apologize in advance when the solution is very easy.
I want to take the url of the current page eg. www.example.com/example.html and put this in a link (among other uses) using javascript.
so it would look like this:
<a href"www.example.com/example.html"></a>
I've tried lots of things I know I need to use location.href but just can't seem to get it to work.
This is the closest I got to getting it to work,:
<a href"javascript:write.location.href;"></a>
Thanks, sorry again. I'm new to JS and html.
J
Name your element with an ID, like: <a id="pageLink"></a> and then when the document loads you can run this snippet:
var link = document.getElementById("pageLink");
link.setAttribute("href", window.location.href);
Or, with something like jQuery:
$("#pageLink").attr("href", window.location.href);
EDIT In response to your question in the comments:
I'm not sure I'm understanding you completely but if it's fixed, then you'd simply concatenate to the href before setting it, e.g.
$("#pageLink").attr("href", staticUrl + window.location.href);
I think you have to use window.location.href. I'm no JS expert, so let me know if it worked.
You can give this a try:
same url link
you can keep the href empty and just use the onclick event.
Hope this helps.
You can use this in href (it's global object) but you can in onclick.
<a onclick="this.setAttribute('href', location);this.setAttribute('onclick', '');">foo</a>
It clear onclick so you get this only once so you can follow the link if you click it again.
you can use document.location.href to find the address of the current page
<a id="cool-link">click it!</a>
<script>
jQuery('#cool-link').attr('href', document.location.href)
</script>
<script>
function gotolink(){
location.href = location.href;
}
</script>
<a href"#" onclick="gotolink();">Click here!</a>

How can I use javascript to convert relative href attributes into absolute paths?

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.
Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...
Right now all of the links are linking to relative paths back to the root.
For example
Home
News
Media
Other
I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?
$("a").each(function() {
alert(this.href);
$(this).attr("href") = this.href;
});
In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:
$('a.external').each(function() {
$(this).attr('href', domain_name + $(this).attr('href'));
})
you don't need jquery for such a simple function....
var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
var relativeLink = eachLink.href;
var absoluetLink = ["http://",domainName,"relativeLink"];
eachLink.href = absoluteLink.join("");
}
something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P
It's very simple:
$('a').each(function(){$(this).attr('href',this.href);});
When you read the href property of a HTMLAnchorElement, you get the absolute path, so you can overwrite it with attr() method of JQuery.
I noticed that all the solutions here only work with href attributes that begin with a "/" character. If you want something more robust, you may want to try the js-uri library. It looks cool but I haven't tried it myself so I don't know how buggy it is.

Categories