css add class to selected element - javascript

I'm using twitter bootstrap and to compose the header I have an like this one
<ul class="nav navbar-nav">
<li>Home</li>
<li class="currentselection">About</li>
<li>Contact</li>
</ul>
The result looks like this:
The LIVE version can be seen here:
Home | About | Contact - LIVE demo
The problem is, I'd like to style one and only one of the <a> that is active, so if the user clicked on About, the <a class="active">About</a> will be styled as active, while the <a>Home</a> will no longer be marked as active. This looks like very common and should be achieved easily, but I've been tinkering for 2 days and really have no idea and coming from C and CPP background, I'm very weak in javascript... would you please explain and mark which file (.css or .js or inside the .html itself) that I can achieve this?
Thank you very much for your help!

You've tagged this with twitter-bootstrap, so does that mean that you have jQuery running? If so, then it's an easy fix.
You just setup the CSS like this:
.nav li a { color: #000; background: #FFF; }
.nav li a.active { color: #FFF; background: #FF0000 }
Then you can change the "active" class on the elements by putting a jQuery listener somewhere in your script. In this case, you're listening for someone to click on it:
$(function() {
$('ul.nav li a').on('click', function(e) {
//this line prevents the link for actually redirecting you
e.preventDefault();
//this line clears whatever the previous active link was
$(this).closest('ul').find('li a.active').removeClass('active');
//this line adds the class to the current link
$(this).addClass('active');
});
});

Related

How do I tell a submenu to be visible when its parents or containing links are active?

I have a menu in HTML and it looks like this:
<nav>
<ul>
<li>Home</li>
<li>About
<ul>
<li>Team</li>
<li>Philosophy</li>
<li>History</li>
</ul>
</li>
<li>Projects</li>
<li>Services
<ul>
<li><a href="#">Our Service</li>
<li>Special Offers</li>
</ul>
</li>
<li>Contact</li>
</ul>
</nav>
Everything is in shape via CSS except one thing: to get the submenu to appear when its parent list-item's link points to the same address as the current page address.
I know this is possible somehow. But I really am the greatest noob with JavaScript or jQuery or PHP (I think the last two mean the same thing right?).
I tried copying and pasting code pieces like "OnClick=..." and one that was like "" or also one I found that contained "GetElenentbyTagName" (which almost worked...) but besides that I had no real clue about where to put them even. They just didn't work properly or not at all. I had a full done code piece but when I pasted it in and replaced some tag names it all got got marked red and my head is burning after trying to get it to work for the entire day.
I think this is possible because I have seen things that seemed to be describing part of what I want to do. E.g.
The script piece should either
Option A: Tell the browser that if the user is on a page which has the same address as a link in the menu it's href-address is, then it's submenu (ul li ul) or the menu (ul) where itself is contained in, should get "visiblity:visible".
Option B:
The script code says like "if the user clicks on an menu item (ul li), then it's submenu (ul li ul), if it has one, or if the menu-item that is being clicked is one of the submenus, then this submenu should become "visibility:visible". If the item that is clicked doesn't have a submenu, no submenu should be shown.
The HTML code must not have classes or other attributes directly anywhere between (nav) and (/nav) though.
I do not have sure if i understand what you need,
you need when user go to some menu page it get the url and active that link on menu until the user is on that page right?
if is that,
i think something like that should work:
<script type='text/javascript'>
$(function(){
$item = $('ul li a').filter(function(){
return $(this).prop('href').indexOf(location.pathname) != -1;
});
$item.css('visibility','visible'); //or whatever ur using to active it.
});
</script>
You can do this with CSS:
li ul {
display: none;
}
li a:hover + ul {
display: block;
}
http://jsfiddle.net/7bxf6r33/
[Edit]
This works:
http://jsfiddle.net/7bxf6r33/7/

Active link after click [duplicate]

This question already has an answer here:
Add ".active" class to the current page's link in a menu using jQuery or PHP [closed]
(1 answer)
Closed 8 years ago.
I cant find a way to add a class to an "a" element of a nav bar.
This is the html nav and the jQuery (applied to test.html url only, to test it):
$(document).ready(function() {
$("a").click(function() {
var actRef = $(this).attr("href");
if (actRef === "test.html") {
$("a[href='test.html']").addClass("active");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<ul>
<li>Inicio
</li>
<li>Test
</li>
<li>Item
</li>
<li> test2
</li>
</ul>
</nav>
This isnt working, it just doesnt do anything, but if i change the .click to .hover it works fine adding the class but doesnt go to the link so the info of the page wont change.
I also tried this: How to change active class while click to another link in bootstrap use jquery? but neither works because of the e.preventDefault();...
If i take out the preventDefault it wont add the class but it will forward to the link...
PD: The aim is to let the user know on which tab he is actually on depending on the menu link he clicked.
Why not use then anchors :active state:
a:active {
/* your .active styles */
}
You code is not working as you are trying to set class on some link using javascript, and then navigating same time. So thing is the part where you are changing class for link is working actually, however you are not able to see it as after navigation html will be reloaded.
To solve this problem , you need write a common function for updating the class of link, in your common html. However, call that function from the html being loaded at onload event instead of calling at click.
Your common js or html will be having function :-
highlightlink(linkid){
$("a[href=' + linkid +']").addClass("active");
}
Each html will call this functin onload with respective htmlname.
For example test.html will hat this code :-
$(document).ready( function (){
highlightlink('test.html')
});
});
While index.html will have :-
$(document).ready( function (){
highlightlink('index.html')
});
});
Once your html is loaded, the that particular html will loaded
Do you really need to add a class to the html element? If it's about styling I think it might be possible to solve your styling using a simple :active pseudo selector. See example below:
li:active {
background-color: #f99;
}
li a:active {
color: #fff;
}
<nav>
<ul>
<li>Inicio
</li>
<li>Test
</li>
<li>Item
</li>
<li> test2
</li>
</ul>
</nav>
So what you can do is you can add a page link in the URL querystring like:
www.example.com/test.html?pageinfo=test.html
Now after the successful page loads you can retrieve page info from the query string and then you can add an active class to the anchor tag.
This way you will get querystring like this pageinfo=test.html and after successful parsing of querystring you will convert the information to {pageinfo:test.html}.
Using that you can add style/class to the anchor tag.
Thanks to #Panther this is easier than i tought:
$(document).ready( function(){
var location = window.location.pathname;
location = location.replace("/", "");
$("a[href='"+location+"']").addClass("active");
});

change Css on click event

I am having several links in asp pages and all links are having respected CSS. the 1st links is highlighted on the Home page with Different CSS. I want to toggle the CSS class on the the Click event whenever i pressed the 2nd or the the 3rd link respectively it should get highlighted and other one become Normal with Normal CSS.
<ul>
<li><a href="../Admin/Home.aspx" id="a_Home" class="homeactive" onclick="ChangeSelectedMenuCss(this.id);">
Home</a></li>
<li><a href="../Admin/subadmindetails.aspx" id="a_Report" class="home" onclick="ChangeSelectedMenuCss(this.id);">
SubAdmin</a></li>
<li><a href="../Admin/control_panel.aspx" id="a_User" class="home" onclick="ChangeSelectedMenuCss(this.id);">
Control Panel</a></li>
<li><a href="../Admin/admin_master.aspx" id="a_CntrlPnl" class="home" onclick="ChangeSelectedMenuCss(this.id);">
Master Data</a></li>
<li>Logout</li>
</ul>
please help me out i m stucked
Thanx and regards.
I think you're confusing how ASP.NET and Javascript interact with each other. When a user clicks on one of those links, the onclick event will fire, but then ASP.NET will load the page that relates to the link, therefore resetting the navigation menu.
What you probably want to do instead of using onclick events is to have a class on your Masterpage that identifies what page it is on, and then add the homeactive class to whatever link it needs to be on.
In order to change class using javascript you can do something like this:
function ChangeSelectedMenuCss(id){
document.getElementByClassName('homeactive').className ="home";
document.getElementById(id).className = "homeactive";
}
If you use JQuery, then this code may be useful for you.
First of all like this code-
$(function() {
var links = $('a.link').click(function() {
links.removeClass('active');
$(this).addClass('active');
});
});
And then in your CSS File, Add tis class-
a, a:visited { color:black }
a.link.active { color:blue; }
It might Help you....
or you can see this fiddle - http://jsfiddle.net/gHb9F/

Make only bullets clickable

I'm working on a menu that is designed using an unordered list, with each list element containing a link to another page. However, I would also like to be able to click on each bullet point to open more subcategories that will also link to other pages.
Essentially, I would like to be able to click once on a link and have it go to the correct page, but I would also like to click on the bullet point and have it expand into the subcategories. I've been researching how to separate the bullet from the content of the li, but it doesn't seem to be working in my case, likely because my li contains a lot of subcategories. Here's an example:
<li id="m2l1" class="child">
Y
<ul id="u11">
<li class="gchild">Y.1</li>
<li class="gchild">Y.2</li>
<li class="gchild">Y.3</li>
<li class="gchild">Y.4</li>
<li class="gchild">Y.5</li>
<li class="gchild">Y.6</li>
<li class="gchild">Y.7</li>
<li class="gchild">Y.8</li>
<li class="gchild">Y.9</li>
</ul>
</li>
Does anyone have any suggestions as to how to separate the bullet from the text in my case?
Here's the link: http://jsfiddle.net/stamblerre/XYp48/17/
Thank you!!!
Your HTML is invalid. You can't have div inside your ul. Moreover, you can greatly simplify your code by moving separate logic for each li into one generic handler.
Something like this:
Demo: http://jsfiddle.net/abhitalks/XYp48/18/
CSS:
ul {
display: none;
overflow: hidden;
}
ul:first-child {
display: block;
}
JS:
$("li").on("click", function () {
$(this).children("ul").slideToggle();
return false;
});
Edit:
I deliberately left out checking of a because clicking the a would navigate to the respective pages (as mentioned in your question), so expand/collapse wouldn't matter.
However, as per your comment if you really want to remove a altogether from the handler, then you can use the event target to handle li without a. Something like this:
Demo 2: http://jsfiddle.net/abhitalks/XYp48/22/
JS:
$("li").on("click", function (e) {
var $t = $(e.target); // get the event target as a jQuery object
if (!$t.is('a')) { // check if the target is not an anchor
$(this).children("ul").slideToggle();
return false;
}
// otherwise if target is anchor, then do nothing
});
Change your list still to hide bullets, then modify your html to :
<li class="gchild">•Y.1</li>
Should do the trick.
<li class="gchild">Y.1</li>
One way that worked for me: remove the bullet with li { list-style-type: none; } then add your own bullets with the character • (alt-8 on a mac). Add that character inside a elements like so:
• X
with the label now outside of the element.
Hope this works for you!

If I have one nav_bar.html file that is included on other pages, how do I show which menu item is active?

thanks for taking the time to read this.
I have a JavaScript (jQuery) navigation bar on my main page that is simply "included" on my page. For example, I have index.shtml that "includes" the nav bar, which is "nav_bar.shtml". And this is the same for every other page. Now clearly, with the current setup, there's no way to show the user which menu item is currently selected since the nav_bar.shtml page stays static.
What I'm wanting to do is STILL have just the one nav_bar.shtml file, but be able to, on the individual pages, show the user the current menu item selected on the nav bar (as in a different shade of color, etc.). If nav_bar.shtml stays static, there's not a very clear way to do this. Is there a workaround to this if I don't want to instantiate an entirely new Javascript nav bar on each and every page? Or would each page need its own version of the nav_bar code specific to that page so it knows which item it needs to shade?
One way to do this is to write some code to look in your menu, find the hrefs of the links therein, and compare them to the current window.location.pathname. If you have nice clean URLs this isn't too hard. If you have long, complex URLs, it may not be workable.
So, here's the general idea:
$(document).ready( function(){
var thispage = location.pathname.substring(1);
$('#menu li a[href~="' + thispage + '"]') // ~= is contains. Tweak as needed.
.addClass('active');
});
Assuming your menu looks something like this:
<ul id="menu">
<li>This</li>
<li>That</li>
<li>The Other</li>
</ul>
And of course:
li.active {
background-color: yellow;
}
I don't know if this is the answer you're looking for. But you don't need any javascript in order to shade certain element in certain page.
You can always take advantage of CSS selectors, for example:
<body id="homepage">
<ul id="tabs">
<li id="tab-homepage">homepage</li>
<li id="tab-news">news</li>
...
In your CSS you can say something like:
#homepage #tab-homepage { background-color: red }
#newspage #tab-news { background-color: blue }
So, finally, you would only have to change the "id" attribute of the body element to get your shaded menu items.
Anyway, if you're using jQuery you can always use something like:
$('body').attr('id', '...');
You could attempt to detect which page the user is currently on by use of window.location.pathname, and shade the relevant menu item based on this.
Example:
function shadeMenuItem(item){
//Your code to style the given element here
}
$(document).ready(function() {
if(window.location.pathname.match(/^\/questions.*/)){
shadeMenuItem($('#questions')); //shade menu item 'questions'
}
else if(window.location.pathname.match(/^\/users.*/)){
shadeMenuItem($('#users')); //shade menu item 'users'
}
});
If this code was implemented on this page, the first condition would be matched, meaning that shadeMenuItem() would have the element with #questions passed to it.

Categories

Resources