Here is my JS code which add an active class to the parent of all <a> objects which contain a href path who match with my current URL.
aObj = document.getElementById('menuG').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
alert("Button n°"+i+" - Value : "+document.location.href.indexOf(aObj[i].href));
aObj[i].parentElement.className='active';
}
}
My problem is that the first button which have href="/" is always active.
The code document.location.href.indexOf(aObj[i].href) always return 0 for the first button and i don't understand why.
Here is my html code :
<ul class="nav navbar-nav" id="menuG">
<li>Mes Fichiers</li>
<li>Historique</li>
<li>Profil</li>
</ul>
Thanks for your time.
Any URL will most likely contain the / of that first link tag. If you use indexOf(), it will find the / in any page of your website. Hence, that first link's parent will always get styled.
You can test it for yourself in the console of your browser. In an HTTPS website, the first match of / is in position 6 (7th character in a URL). indexOf just returns the position of the first match, and the / that's the href of your first link will always get a match.
You could replace the href of the first link with something like index.html, and then force a redirect from http://example.com to http://example.com/index.html. Your other bet is to change the way you check if this is the current page, by, for example, checking if window.location.href is strictly equal (===) to the href of a link tag: window.location.href === aObj[i].href.
Related
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
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)
}
}
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')
});
});
I've managed to get it so when I click on say "about" then it adds the class that I've called "active" however it doesn't remove the previous "active" on the home page link
Here is my HTML
<nav id="main-nav" role="navigation">
<ul>
<li>
Home
</li>
<li>
About
</li>
<ul>
</nav>
and here is my javascript
function setActive() {
aObj = document.getElementById('main-nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
Basically what I want to be able to do is the following:
When on homepage it adds the class "active" so that I can highlight the link with CSS.
Then when I click on About it removes the "active" class from home (thus removing the highlighted css) and adds the "active" class to about (thus adding the highlighted css).
Just add aObj[i].className = ""; before the if condition.
function setActive() {
aObj = document.getElementById('main-nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
aObj[i].className = "";
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
What this is basically doing is removing every class from all the links and only adding the 'active' class if it's the correct page. But since it seems the page is refreshing, I don't know how the class would persist from one page to the other, so it would be helpful to have a link to the code.
I checked the source of your page and I think the problem lies in the way the links are created (the JavaScript code you have posted is okay).
PROBLEM : The URL of the "Home" tab is
https://dhctranslations.com/
And the other URLs (hrefs) on the navigation are
About Tab - https://dhctranslations.com/about
Certified Translation Tab - https://dhctranslations.com/certified-translation-services
Pricing Tab - https://dhctranslations.com/pricing
...
...
The check you are doing in your function is 'indexOf' check. That is why the condition always returns true for the 'Home' tab (as this part of the URL is common to all other links).
SUGGESTION : To remedy this you can either change the 'indexOf' check and replace it with equality check in your code
OR change the URL of the 'Home' tab to something like
https://dhctranslations.com/home
Please note that these are just my suggestions and I am pretty sure that you can work out a solution that suits better to your application's design/architecture.
UPDATE : Here is the modified code that works (Please note this is just to give you an idea and is not a clean solution at all)
aObj = document.getElementById('main-nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
aObj[i].className = "";
// Changed the condition
// Concatenated the "/" for comparison as the array does not have trailing "/"s stored
if(document.location.href === aObj[i].href+"/") {
aObj[i].className='active';
}
}
Here's what I have so far:
<script type="text/javascript">
if ($("{CurrentPage}").length > 1) {
$("#comslider_in_point_234708").style.display="none";
}
</script>
Here are tumblr's variables (I'm not sure which one to use, as none seem to work):
{block:Pagination}{/block:Pagination}
Rendered if there is a "previous" or "next" page.
{block:PreviousPage}{/block:PreviousPage}
Rendered if there is a "previous" page (newer posts) to navigate to.
{block:NextPage}{/block:NextPage}
Rendered if there is a "next" page (older posts) to navigate to.
{PreviousPage}
URL for the "previous" page (newer posts).
{NextPage}
URL for the "next" page (older posts).
{CurrentPage}
Current page number.
{TotalPages}
Total page count.
You already got an answer, but I think we can do better than just give you the code.
One problem with your JavaScript was that you were trying to get a HTML element with the jQuery selector, and the Tumblr variable isn't a HTML element, it's just a variable. Then we've removed the jQuery element selector from your code, like this:
if ({CurrentPage}.length > 1) {
document.getElementById("comslider_in_point_234708").style.display="none";
}
But your code will still have other problem, because this way you are checking if the variable length property is greater to 1, not the variable actual value, so if the variable is equal to 2 or 9 for example, the comparison will return false and cause the if to fail.
This occurs because the length property return the number of characters in the variable, not it's value (so 10.length returns 2 and 1000.length returns 4). To solve this problem, we've also removed it, leaving you code like this:
if ({CurrentPage} > 1) {
document.getElementById("comslider_in_point_234708").style.display="none";
}
Then when the code is executed in the 11th page, the {CurrentPage} variable will contain the number 11 and the code will run as:
if (11 > 1) { // returns true
document.getElementById("comslider_in_point_234708").style.display="none";
}
Also, if you are using jQuery, you can improve your code by replacing the line inside the if with this:
$("#comslider_in_point_234708").hide();
...That uses the jQuery selector that you've used in the wrong place before, and jQuery's hide() method, that is equivalent to display:none.
So, finally, here's the result:
if ({CurrentPage} > 1) {
$("#comslider_in_point_234708").hide();
}
Post Offsets
Its possible to do this with Tumblrs own theme operators, rather than javascript. The block, {block:Post[1-15]}, allow you to specify a post offset. From the OPs example, I would use Post2.
<style>
<!-- Hide comslider if there is a second post on the page -->
{block:Post2}
#comslider_in_point_234708 {
display: none;
}
{/block:Post2}
</style>
Reference
Posts Basic Variables
Try this:
<script type="text/javascript">
if ({CurrentPage} > 1) {
document.getElementById("comslider_in_point_234708").style.display="none";
}
</script>
No need to use length in the function