add class on li remove after page load - javascript

I am using jquery to add the class to active css on "li" and also navigate to an html page.but after page navigates the class disappers on "li". I have tried different ways to resolve this but couldn't get the point.
$(document).ready(function(){
$( '#topList ul li' ).click(function() {
alert($(this).attr('id'));
if($(this).attr('id') == "add") {
document.location.href = 'localhost:8080/add';
$(this).attr('id').addClass("active");
}
});
});
here is the menu list, what I want is when I click on li it should call a page add and also add a class on that li.
html code
<ul class="nav">
<li class="" id="add"></i> Add </li>
<ul>

You need to add class for the li in the page you are calling ie, the page will be rendered when you call localhost:8080/add.
Because in your code setting up of active class wont be called since the localhost:8080/add will start loading in the previous line of code (document.location.href = 'localhost:8080/add';)
If the page to be rendered is static page then, add this code in that page.
$(document).ready(function(){
$('#add').addClass("active");
});

Use the following script on the page where you have menu or the links.
<div id="cssmenu">
<a href="blah blah" > Test page</a>
<a href="blah blah" > Test page</a>
</div>
$(document).ready(function () {
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
$('#cssmenu a').each(function () {
if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
$(this).addClass('active');
});
});

I solved this problem on my website by looking at the URL and deciding which of the navigation elements was best to add.
function showContent(target) {
var e = $('#'+target);
$(".content").hide();
$("#nav li.active").removeClass("active");
$("#nav li[target='"+target+"']").addClass("active");
e.toggle();
ga('send','pageview',window.location.pathname+"#"+target);
}
// this looks at the URL (by the #...) and decides which view is active
// this gets called on ready and if the client hits the link
// (which dynamically loads instead of making a trip for a new page to the server)
$(window).hashchange(function() {
var which=window.location.hash.substring(1);
switch( which) {
default:
which="profile";
case "profile":
case "resume":
case "projects":
case "contact":
showContent( which);
}
});

Related

How can I combine .toggleClass() with .appendTo()?

I append a new class to a HTML container. How can I toggle this on/off by clicking on the menu button?
And is it even "best practice" to write more complex HTML code in JavaScript or would you prefer another method for this? Because I plan to do this for some more containers. Thank you!
$(document).ready(function() {
$( "a.header-login" ).click(function() {
$("<div class='sub-menu'>" +
"<h2>Hi x!</h2>"+
"<a class='item' href='#'>Logout</a>"+
"</div>")
.appendTo("header .header-r");
})
});
I want to accomplish that another click on "a.header-login" deletes the container ".sub-menu". Now, it is always generated when you click "a.header-login"
In this case you need to add a condition to check whether or not the element already exists. If it doesn't create it, if it does remove it.
jQuery(function() {
$('a.header-login').click(function() {
var $target = $('header .header-r .sub-menu');
if ($target.length === 0) {
$('<div class="sub-menu"><h2>Hi x!</h2><a class="item" href="#">Logout</a></div>').appendTo('header .header-r');
} else {
$target.remove();
}
})
});
That being said, you can make this much simpler logic if you always include the .sub-menu in the HTML of your page but hide it with CSS by default. In that case your jQuery would become a simple call to toggle():
jQuery(function() {
$('a.header-login').click(function() {
$('header .header-r .sub-menu').toggle();
})
});

Check if other tabs are open

I've tried coding a function that checks if other tabs are active, and if they are it should close them and open another tab, and if not it should just open the tab. I'm new at javascript and tried this but it didn't work.
HTML
<div class="showRatings">
<li role="presentation id="productInfomation" class="active">...</li>
<li role="presentation id="productDiscount">...</li>
<li role="presentation id="productRatings">...</li>
Js Script
$('div.showRatings').click(function(){
if ( document.getElementById('productInfomation').classList.contains('active') ) {
document.getElementById('productInfomation').classList.remove('active');
document.getElementById('productRatings').classList.add('active');
} else if ( document.getElementById('productDiscount').classList.contains('active') ) {
document.getElementById('productDiscount').classList.remove('active');
document.getElementById('productRatings').classList.add('active');
} else {
document.getElementById('productRatings').classList.add('active');
}});
You don't need to write code for each element separately, or even bother to test which tab was previously active. Just remove the "active" class from all of them in one go, and then add it to the element that was clicked:
$('.showRatings li').on("click", function() {
$('.showRatings li.active').removeClass('active');
$(this).addClass('active');
}

Onload bootstrap tab trigger

The active class isn't working and I've tried body On-load click trigger and obviously show tab using id and many other ways, however nothing seems to be working. I have hashed the URL to enable tabs to be linked individually in the search. Any help is much appreciated.
JS: to hash the URL and jump to tab
// jump to tab if it exists
if (location.hash) {
$('a[href=' + location.hash + ']').tab('show');
}
// add tab hash to url to persist state
$(document.body).on("shown.bs.tab", function(e){
location.hash = e.target.hash;
});
});
JS: To go to tab home (not working)
$("document").ready(function(){
$("#home").trigger("click");
});
HTML:
<div class="col-xs-5 col-md-2 nopadding">
<nav class="nav-sidebar">
<ul class="nav tabs">
<li class="lead3">Home </li>
<li class="lead3">tab1</li>
<li class="lead3"><a href="#tab3" data-toggle="tab" >tab3</a></li>
<li class="lead3"> Contact </li>
</ul>
</nav>
tab-pane:
<div class="tab-pane active fade text-style" id="home"> . .. </div>
What you expect from this line?
$("home").trigger("click");
I suppose Jquery can't find element here $("home"). You could evaluate it in console for check.
if you are going to find element with class 'home' or id 'home' then you should use $(".home") or $("#home") properly.
It looks like your Document Ready event doesn't work.
Try remove the quotes around the $("document").
A shorter method for this event is as follows:
$(function() {
});
I know that this is very late but I'd like to post my solution since this was something that I was stuck on as well. There's an important subtlety that I think is easy to miss. You want to trigger the click on the <a> tag inside the nav, not the actual panel. Remember you click on the tab not on the panel to trigger it into view. So to get the correct tab to show when the user navigates to /my/path#home you want to bind on the hashchange event and click the correct element. See https://stackoverflow.com/a/680865/5262119 for more info on binding to the hashchange event.
$(window).bind('hashchange', function(event){
var hash = window.location.hash;
// get the actual anchor tag that links to the panel
var $matchingAnchor = $('nav a[href^="' + hash + '"');
if ($matchingAnchor) $matchingAnchor.click();
});
And assuming you want to restrict this to trigger only a certain page then you can add a location check:
$(window).bind('hashchange', function(event){
var path = window.location.pathname;
var hash = window.location.hash;
var $matchingAnchor = $('nav a[href^="' + hash + '"');
var contextRegex = /my\/page/;
var correctPage = contextRegex.test(path);
if (correctPage && $matchingAnchor) $matchingAnchor.click();
});
I imagine you also want to make sure that clicks on the tabs update the hash in the URL window so bind to the tabs event:
$('nav a').on('click',function() {
var $a = $(this);
var hash = $a.attr("href");
window.location.hash = hash;
});
This would go inside your ready function. You will also have to make sure that the function that triggers the click happens when the page first loads.
Complete solution:
$(document).ready(function() {
// Declare clickback function
function triggerTabClick() {
var path = window.location.pathname;
var hash = window.location.hash;
var $matchingAnchor = $('nav a[href^="' + hash + '"');
var contextRegex = /my\/page/; // or whatever you want this to be
var correctPage = contextRegex.test(path);
if (correctPage && $matchingAnchor) $matchingAnchor.click();
}
// Trigger it when the hash changes
$(window).bind('hashchange', triggerTabClick);
// Trigger it when the page loads
triggerTabClick();
// Hook into click for tabs to make sure hash is updated on click
$('nav a').on('click',function(event){
event.preventDefault();
var $a = $(this);
var hash = $a.attr("href");
var window.location.hash = hash;
})
})

JavaScript to highlight active page

I am trying to utilize JavaScript to highlight the current page. I have a main menu and a sub menu on the page. I want the highlighted main menu to look different from the sub menu. Here is the JavaScript I came up with the apply a css class to the current page. How do I get the JavaScript to differentiate the two different classes?
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('main_current');
}
});
});
</script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('sub_current');
}
});
});
</script>
It really depends on the page/code structure you're going for. I usually don't check window.location, but instead set rel attribute on the page body. On homepage body will have rel="home", on some other page rel='other-page and so forth.
This way you can check for body's rel attribute and change menu/submenu's status based on that.
(function(){
var currentLocation = $('body').attr('rel');
switch(currentLocation){
case 'home':
//add class to the home link
break;
case 'other-page':
//add class to the other link
break;
}
})();
Specify better the selector when you iterate over the submenu and override some properties with 'sub_current'. EG:
If you have
<ul id="menu">
<li>ThisMenu
<ul id="sub-menu">
<li>ThisSubMenu</li>
</ul>
</li>
</ul>
you could specify with $('#sub-menu a').
I hope it helps.
cheers
The method below will do the same thing
$(function() {
var url = document.location.href;
if (url.indexOf("about") > -1) {
$('#nav-bar ul li:contains("About")').addClass('sub_current');
}
else if (url.indexOf("index") > -1) {
$('#nav-bar ul li:contains("Home")').addClass('main_current');
}
else {
// do something else
}
});
Note: :contains selctor is case sensitive.

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

Categories

Resources