I am looking for a way to add an active class to the tag that has an href of the current page.
Say I am on the page localhost:3000/inbox, I need my html to change add the correct class to the correct which are all located in the div with the class sidebar.
So when at "/inbox" jQuery should make my html look like this:
<div class="sidebar">
<a href="/link">
<i class="fa fa-inbox"></i>
<span>A Link</span>
</a>
<a class="active" href="/inbox">
<i class="fa fa-inbox"></i>
<span>Inbox</span>
</a>
</div>
This is what I tried, but it doesn't work, it breaks the code:
var href = $(location).attr('href');
('.sidebar').find('a[href*=href]').addClass("active");
Thank you. Please let me know if I wasn't clear enough.
It looks like you're almost doing it right, with the minor mistake of forgetting to call jQuery or $. You also need to concatenate your selector, so that the value of href is searched for.
$('.sidebar').find('a[href*="' + href + '"]').addClass('active');
You probably also need to find just the path name to match your href values, like so:
var href = window.location.pathname;
How about this?
var path = window.location.pathname;
$(".sidebar a[href*='"+path+"']").addClass("active");
Please note the ' around the path. They are there because jQuery cause syntax error if there are unquoted / in the selector.
When I try it on JSFiddle, I get a / at the end of the path. You might want to add that to your links, or you can remove it from the path variable like this:
if(path.charAt(path.length-1) == "/")
path = path.substring(0, path.length - 1);
Then some browsers might not include the leading / (or at least I think so), so you might want to add it in case it isn't already there:
if(path.charAt(0) != "/")
path = "/" + path;
Since you use *= you might match more than the current page. For instance, if you are on /inbox/ you will also add the class to links to /inbox/sub/folder. To avoid this, use = instead.
Taken together, you would get this:
var path = window.location.pathname;
if(path.charAt(path.length-1) == "/")
path = path.substring(0, path.length - 1);
if(path.charAt(0) != "/")
path = "/" + path;
$(".sidebar a[href='"+path+"']").addClass("active");
Here is a working JSFiddle. (You might need to press run to make it work, as the URL is different the first time the page load.)
As far as I understand your question you want to change all divs that have a href of '/inbox' to have the class "active"
Your code should therefore look like this
$(document).ready(function(){
$(.sidebar a[href=='/inbox']){
$(a[href=='/inbox').addClass('active');
}
}
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 want to give variables from html to python using javascript.
On clicking navbar coded as:
aa.html
<a href="{{url_for('to_python')}}" id='aa'>hello</a>
Where to_python route goes to bb.html
I want to pass variable animal='dog' when clicking on aa.html href.
I tried using
$("#aa").attr("href", '?animal=dog')
But this does not go to bb.html.
The result is aa.html?animal=dog ( I want bb.html?animal=dog)
※Also I would like to know a way to pass variables on method POST using javascript. Any Ideas?
I tried using
$('#aa').on("click", function(){
$.post('/to_python', {animal:'dog'}, function(res){
.....something
}
But this code sometime work, but sometimes not. Do not know what is wrong.
If you want to change the URL using JavaScript, try something like
var $aa = $("#aa");
$aa.attr("href", $aa.attr("href").split("?")[0] + "?animal=dog");
That is, instead of replacing the href, grab everything before any parameters it might already have, then replace the parameters with what you want. For example,
<a href="hello"> would become <a href="hello?animal=dog">
<a href="hello?parameter=yes"> would become <a href="hello?animal=dog">
etc. If you need to retain other parameters, you'll need to do a little bit more:
var $aa = $("#aa");
var currentHref = $aa.attr("href");
$aa.attr("href", currentHref + (currentHref.indexOf("?") == -1 ? "?" : "&") + "animal=dog");
This way
<a href="hello"> would become <a href="hello?animal=dog">
<a href="hello?parameter=yes"> would become <a href="hello?parameter=yes&animal=dog">
Hi Wonder if anyone can point me in the right direction.
I'm after some code that I can put on a link that will go to the current page url but in a separate folder or add a language identifier into the url.
So for example, if someone is on FAQ.aspx , they click the Italian link in the menu and it will send them to it-FAQ.aspx or /it/FAQ.aspx and the same for other pages.
Does that make sense? and is it possible, and can someone point me into the direction of where to look
Thanks in advance!
Try something like this :
Get first pathname of the current url, then put language code in front and change href of the link with jquery :
<html>
<a class="switch_language" data-country-code="it" href="">Italian</a>
<a class="switch_language" data-country-code="de" href="">German</a>
and...
<script>
$('.switch_language').each(function() {
$(this).attr('href', $(this).attr('data-country-code') + '/' + location.pathname);
});
Your urls of the language links will be look like this
/it/faq.aspx
/de/faq.aspx
Using a data attribute, you can store the "part to add to the URL" on the link. You can read it using the .data() method.
Then... If you split the actual URL by the /, you can reassemble it and insert the part to be added.
This script will works on any page.
$(".menu .lang").on("click",function(){
// Get the actual page URL
var thisPage = location.href;
console.log(thisPage);
// Split the URL by the "/"
var splitted = thisPage.split("/");
var splittedLength = splitted.length;
// Get the data-lang value
var insert = $(this).data("lang");
// Re-assemble the URL except the last part
var destination="";
for (i=0;i<splittedLength-1;i++){
destination += splitted[i]+"/";
}
// Add the part to "insert" and last part of the URL
destination += insert+"/"+splitted[splittedLength-1];
// OR
// destination += insert+"-"+splitted[splittedLength-1]; // See explanation below the snippet.
// Go to that page!
console.log(destination);
//location.assign(destination); // Commented for this demo...
});
.menu a{
display:block;
text-decoration:underline;
cursor:pointer;
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>FAQ</h1>
<div class="menu">
<a class="lang" data-lang="it">Italiano</a>
<a class="lang" data-lang="en">english</a>
<a class="lang" data-lang-"fr">Français</a>
</div>
Here, the language parameter is added in between / like a it's a directory... But you can easilly add it to the page name like it-FAQ.aspx.
When the URL has #id-name-here I want to apply a CSS class to the parent of that target on the page.
So given this URL...
domain.com/#Domain
Then the page will jump to this location in the page
<a name="Domain"></a>
I want to find the PARENT of <a name="Domain"></a>
So using javaScript I want to find the Parent of this Node like this...
$('a[name="Domain"]').parent('.module-box').addClass('active-cat');
which will add the class active-cat to the Parent of my target Node.
So I need help making this more Dynamic, so Domain could be any value...
I am able to get the Domain portion from the URL with location.hash.
Then do this....
var activeCat = location.hash;
$('a[name="' + activeCat + '"]').parent('.module-box').addClass('active-cat');
This almost works except my activeCat contains the # and I need to remove that.
So if someone can help me....
Remove # from var activeCat = location.hash;
Check to make sure var activeCat = location.hash; even exist before running the other code?
My end result...
Just remove that #:
var activeCat = location.hash.replace('#', '');
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.