Active link after click [duplicate] - javascript

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");
});

Related

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!

css add class to selected element

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');
});
});

Use JavaScript to change the class of an <li>

I have the following code:
<div id="nav">
<ul>
<li id="tabOne" class="first current">Page One</li>
<li id="tabTwo">Page Two</li>
<li id="tabThree"><a href="./CS3.html" target="SheetView">Page Three</li>
<li id="tabFour">Page Four</li>
<li id="tabFive">Page Five</li>
<li id="tabSix">Page Six</li>
</ul>
This loads the selected page into an iframe named "SheetView." What I need to do is use JavaScript to alter the class when an option that isn't the currently selected on is clicked. I should say that I have the current class already setup in my CSS. I just have no way to trigger it.
I thought adding an onlick event to the <UL> up there and calling onclick="Javascript:changeCurrent();" but there is the problem (four actually):
Is <ul onclick="JavaScript:changeCurrent();> where I need to have the event?
What is the resulting JavaScript to make the change happen?
How can I cause the first option to be set as current by default?
Is there a way to keep the currently selected option from being an active link?
I found a few different examples but I couldn't tailor them to work for me. Any help would be most appreciated.
Since you specified that you wanted a non-jQuery response, here's a function that will toggle appropriately:
function toggleNavSelected(el){
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var cur = list.children[i];
if(el==cur){
cur.classList.add("current");
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
return false;
});
} else {
if(cur.classList.contains("current")){
cur.classList.remove("current");
}
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
}
}
Either add an onclick handler to each LI (onclick="toggleNavSelected(this);") or execute the following after the menu has loaded:
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var el = list.children[i];
el.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
Demo: http://jsfiddle.net/bWY7P/2/
(note: The JSFiddle script has a small difference; it adds a return false; to the onclick function so that you can play with it without the links actually following the HREF attribute. Do not use that line in your live code)
Explanation:
The function looks at each LI element within the #nav element.
If that element is the element passed to the function, then it adds the class .current.
Otherwise, it removes the class .current (if present).
The second part binds a function to the onclick event of each a element that calls the toggleNavSelected() function and passes its parent element (the li) as the argument.
1) if you want to change the currently selected class when you click an item, put the onclick into the li item
2) using jquery would be very easy here, all you have to do is import the jquery file with the <script> tag and you're ready! For example, you could do onclick="changeClass(this);" on the <li> tag and in a normal JavaScript file or in a script tag:
function changeClass(this){
$('#nav li').attr("class","");
$(this).attr("class","current");
}
Replace the 'current' with the class name you want to use
3) it should already be set as current
4) use the :visited CSS selector to change what colour followed links look like eg:
a:visited{
color: #000000;
}
First of all you should set the event handler from a separate script, not from an onclick attribute. You don't repeat your code that way and have anything in one place. The HTML is also much cleaner.
Using jQuery it would be as easy as:
var menuLinks = jQuery( '#nav a' );
menuLinks.on( 'click' function() {
menuLinks.removeClass( 'active' );
$( this ).addClass( 'active' );
} );
You could also do that in plain JS, but using some library keeps you out of the trouble of browser incompatibilities.

javascript driven navigation menu on footer

My navigation menu on header looks like this:
<ul id="nav">
<li id="home">
<a class="mainmenu" href="#">Link1</a>
</li>
<li>
<a class="mainmenu" href="#">Link2</a>
</li>
</ul>
and the same markup is used for the footer section and it's not working.
I have also a file called jscript.js which contains all the javascript for the website,
and I found this variable:
var navTarget = "ul#nav li a" //menu link to target
Also, if I remove for example the markup in the header sections the footer will work.
I've tried also to use .nav instead of #nav and I have the same problem.
The navigation menu is controlled by javascript, I don't post the code here because it's huge, for better understanding of how the navigation menu works look here
I've found this in the javascript:
//SET MENU ITEM IDs
$(navTarget).each(function(i){
i++
this.id = this.id +"_" +i ;
});
//MENU CLICK FUNCTION
$(navTarget).click(function() {
//ensure link isnt clickable when active
if ($(this).hasClass('active')) return false;
//get id of clicked item
activeNavItem = $(this).attr('id');
//call the page switch function
switchContent();
});
//CONTENT SWTICH FUNCTION
var switchContent = function (){
//set previous and next link & page ids
var PrevLink = $(navTarget+'.active')
$(PrevLink).removeClass('active');
var PrevId = $(PrevLink).attr('id');
//alert(PrevId)
var NextLink = $('#'+activeNavItem).addClass('active');
var NextId = activeNavItem
//alert(NextId);
From the looks of it, the JS code is using some CSS selector (like jquery's $ or dojo's dojo.query) that pulls in the DOM element target based on the value of navTarget, and then does something with it: turns it into a menu.
But its only doing it once.
You need to look at the JS and see where navTarget is used. Then it should be fairly easy to make it do the menu creation on all the results of $(navTarget) instead of just the first hit.
Also, you should only have on instance of an ID in your dom.
You can change this to a class instead:
var navTarget = "ul.nav li a"
And in the markup:
<div class='nav'>
But you will still have to look at the JS and make sure it functions against a set of targets returned by the CSS selector. That code is probably expecting just a single result and using just it: results[0].
You can only have one element of a given id on the page. So based on your description, it sounds like you have 2.
I don't know exactly how this script works, but you can try using classes instead.
<ul class="nav">
var navTarget = "ul.nav li a";
You would have to change your HTML and the JS navTarget selector string.
But there is also a good chance that your script may not support creating multiple menus at all. And if thats the case, you may need to fix that script or find a better one.
If the code for the footer really is identical to the header, that's the problem. An id should only be used for a single element in a page, and jQuery's selectors will only return the first. Meaning code like "ul#nav li a" only works on the header.
Easiest solution is to change the id's to classes, e.g.:
<ul class="nav">
... and change your jQuery to match that, e.g.:
var navTarget = "ul.nav li a";
Update: And (ignoring that this may end up turning into three duplicate posts), that fix is probably not enough at all, since other parts of the script may only work with a single menu.

Categories

Resources