Dynamically change href and link to a url fragment - javascript

Hope someone can help.
I'm trying to dynamically change hrefs on a page and then point the user to a url which includes a fragment as:
$(document).ready(function(){
if (document.location.pathname.indexOf('cab2') > -1){
document.getElementsByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab2/#linkResources');
} else {
document.getElementByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab/#linkResources');
};
});
In the HTML I'm using several links like this:
<a class="resourceLink" href="" title="Link to Resources section" target="_blank">Resources</a>
What I was hoping for was the script would check what url the visitor had used to arrive at the site, either
http://www.myserver.net/cab/ or,
http://www.myserver.net/cab2/ and then set the appropriate hrefs to either:
http://www.myserver.net/cab/#linkResources or,
http://www.myserver.net/cab2/#linkResources
What happens though is the link opens up the base page (www.myserver.net/cab or cab2) and not the #fragment page.
What am I doing wrong?
My thanks for your interest.

.getElementsByClassName() returns an HTMLCollection, not a single element. You can use .each() to iterate all .resourceLink elements, .attr() to set href attribute value
$(document).ready(function(){
var link = document.location.pathname.indexOf('cab2') > -1 ? "cab2" : "cab";
$('.resourceLink')
.each(function() {
$(this)
.attr('href','http://www.myserver.net/'+ link +'#linkResources')
});
});

Related

Why will the colour of the active link not highlight blue? [duplicate]

I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The tag looks like
<a onclick="return follow(this);" href="sec/IF00.html"></a>
and a JavaScript function that looks like
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
I would expect that item.href would just return a short string of "sec/IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <a> tag? Or do I lose that by natural HTML behavior?
I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex href="page.html" vs. href="sub/page.html"), so I cannot always just remove every thing before the last slash.
You may wonder why I am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <a> tag), then I could probably just insert an extra field into the tag, like link="sec/IF00.html", but again, that would be a little messier.
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
document.getElementById("link").getAttribute("href");
If you have more than one <a> tag, for example:
<ul>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.
This code works for me to get all links of the document
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.
$(".test a").on('click', function(e) {
console.log(e.target.href); // logs https://www.test.com/#test
console.log(e.target.hash); // logs #test
});
The href property sets or returns the value of the href attribute of a link.
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html

How to check if link is present on a page with Jquery?

I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'
You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}
I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}

Append string to every url on page load

I have my website in English but want to show it in Spanish when page loads. So, I got a script from Google Translate that I put in my header file but I need to append some #googtrans(en|fr) at the end of every URL. What I've done so far is:
$(document).ready(function () {
$('a').each(function () {
this.href += '#googtrans(en|es)';
})
});
But a problem with this code is, it is blocking my popups and bootstrap dropdowns.
Is there any simple way to put that trailing string to every URL on page load.
Filter out links that have attributes or classes you don't want the hash applied to:
For example:
$('a').not('[data-toggle], [href^="#"]').prop('hash','#googtrans(en|es)');
If selectors in not() aren't enough you can use the more robust filter() method
A more ideal approach would be being able to have classes on your <a> to represent the ones you do want modified.
<a class="translate">
$('a.translate').prop('hash','#googtrans(en|es)');
OR
<div class="translate">
<a>
</div>
$('.translate a').prop('hash','#googtrans(en|es)');
Note that using the hash property achieves the same as concatenating href
Without seeing more of your html it is hard to provide a lot more help
Now you replace with this code all <a> tags.
Best way - it's taking Google Translator block links on other div, like this:
<div id="gtr">
...
</div>
And Script:
$(document).ready(function () {
$('#gtr a').each(function () {
$(this).attr('href', $(this).attr('href')+'#googtrans(en|es)');
});
});
Instead of
this.href += “#googtrans(en|es)”;
Try this:
$(this).attr("href", $(this).attr("href") + "#googtrans(en|es)");

Highlighting current link

Hi I have to use only html and javascript. I have created one single page which contains a top navigation links the url for those links are something like:
domain.com,
domain.com/b1,
domain.com/b2
how do I highlight the current link.
If I understend question you may try html-attribute style for link tag:
<a style="color: red">link</a>
OR edit CSS-file for that link.
You can set class with serverside and define this class into CSS.
If coding only JS see for JS-object window.location.
You'll need to use a simple JS script to check the href of the link and compare it to the window.location.href (the current URL).
Here's a simple example using JQuery:
var currentUrl = window.location.href;
$('a').each(function(index) {
var url = $(this).attr("href");
if (url === currentUrl) {
$(this).addClass("current");
} else {
$(this).removeClass("current");
}
});
Here it adds a class current to the link if it is the current link. I have a demo here on JSFiddle.
Using jquery
$('a[href="' + window.location.pathname + '"]').addClass('highlight');
replace pathname by one property (or a combination of properties) of the location object if it's not the good one.
the snippet add 'highlight' class to the link with the specified href, then you can write some css to highlight your link.

Setting active link dynamically on static navigation

I have "navigation.html" (static coded navigtaion ) file loaded on multiple pages, using jQuery .load()
Now I need to dynamically set active <li> for each page user clicking on. I can not use body id for specific reasons.
Any other ways to do this?
If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.
changeActiveLink is defined in JS (ex:init.js) file which you include to each page
function changeActiveLink() {
var currentLocation = window.location.href;
currentLocation = currentLocation.replace('//', '/').split('/');
var page = currentLocation[currentLocation.length - 1];
if (page == "") { page = 'index.html'; }
$('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}
This line is called from each file when "init.js" is included.
$('#leftNav1').load('navigation.html', changeActiveLink);
Or you can use any HTML or even HTML5 tag to specify li item.
<li class="some">
or
<li title="some">
or
<li attr-specify="some-specific-in-url">
and jQuery with window.location object
$('li[title="' + window.location.path + '"]').addClass("active");
You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active.
This of course will only work if your href matches the url

Categories