I'm trying to figure this out, but for the life of me I'm confused. I have this:
<!-- Sidebar Menu -->
<ul class="sidebar-menu">
<li class="header">HEADER</li>
<!-- Optionally, you can add icons to the links -->
<li class="active"><a href="res/link.php"><i class='fa fa-link'></i>
<span>Links</span></a></li>
<li><i class='fa fa-link'></i> <span>Another Link</span></li>
<li class="treeview">
<a href="#"><i class='fa fa-link'></i>
<span>Multilevel</span> <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>Link in level 2</li>
<li>Link in level 2</li>
</ul>
</li>
</ul><!-- /.sidebar-menu -->
and my javascript:
var hash = window.location.hash.substr(1);
var href = $('.sidebar-menu li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
$('.sidebar-menu li a > .treeview li a').click(function(){
and I'm having trouble with this line:
$('.sidebar-menu li a > .treeview li a').click(function(){
I want the sidebar-menu menu clickable for all li's with a tags however when I click on the treeview menu, it fires up as an href link. I don't want that clickable.
Am I using the greater than less than symbols correctly in my JavaScript?
use this to prevent default href action
$(your selector).click(function(e) {
e.preventDefault();
// e for event
// preventDefault will stop default href action
});
edit: or you can handle all # links with this selector and preventDefault
$('.sidebar-menu a[href="#"]').click(function(e){
e.preventDefault();
});
selector a[href="#"] will select only A-tags with param href == "#", then just use preventDefault() on them to stop default href action
If you want only elements directly under your selector, use >.
This will select only a tags directly in the li tags that are directly in the sidebar-menu:
$('.sidebar-menu > li > a')
Your first onclick can look like this:
var href = $('.sidebar-menu > li > a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
Your second one can just look like this:
$('.treeview li a').click(function(){
// do stuff.
});
It depends on how much nesting you'll do, but this will apply to all a tags in your treeview, regardless of nesting level.
EDIT:
I see you didn't want the tree clickable at all. In that case, you shouldn't use the a tag at all. Use something like a span with styling that makes it look like a link. Links (a) go somewhere. If you aren't going somewhere, don't use the a.
fiddle: https://jsfiddle.net/6njj7L9g/2/
snippet:
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('.sidebar-menu li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
$('.sidebar-menu > li > a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
.treeLink{
text-decoration: underline;
color: blue;
cursor: pointer;
}
<!-- Sidebar Menu -->
<section>
<ul class="sidebar-menu">
<li class="header">HEADER</li>
<!-- Optionally, you can add icons to the links -->
<li class="active"><a href="res/link.php"><i class='fa fa-link'></i>
<span>Links</span></a></li>
<li><i class='fa fa-link'></i> <span>Another Link</span></li>
<li class="treeview">
<a href="#"><i class='fa fa-link'></i>
<span>Multilevel</span> <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li><span class="treeLink">Link in level 2</span></li>
<li><span class="treeLink">Link in level 2</span></li>
</ul>
</li>
</ul><!-- /.sidebar-menu -->
Make href="" and not href="#" if you don't want it to be click-able.
Related
jQuery doesn't process dynamically added anchor tags. The <li> <a> tags are added more dynamically. The below code works to add attributes for the anchor's tags that are already there but more pagination is added by XHR AJAX calls and the .each() function doesn't work.
$(document).ready(function () {
$("ul.page-selector-list li a").each(function () {
var pageText = $(this).text();
$(this).attr("aria-label", "click here for " + pageText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="page-selector-list">
<li class="page-selector-item-first inactive">First</li>
<li class="page-selector-item-previous inactive">Previous</li>
<li><a class="page-selector-item-link active" data-offset="0" data-itemnumber="1" href="#">1</a></li>
<li><a class="page-selector-item-link" data-offset="10" data-itemnumber="2" href="#">2</a></li>
<li><a class="page-selector-item-link" data-offset="20" data-itemnumber="3" href="#">3</a></li>
<li><span class="page-selector-more">...</span></li>
<li><a class="page-selector-item-link" data-offset="2020" data-itemnumber="203" href="#">203</a></li>
<li class="page-selector-item-next">Next</li>
<li class="page-selector-item-last">Last</li>
</ul>
Please try below code when you find your code is not working after AJAX:
$( document ).ajaxComplete(function() {
$('ul.page-selector-list li a').each(function(){
var pageText = $(this).text();
$(this).attr('aria-label', 'click here for '+ pageText);
});
});
Please let me know if you find any issues.
I am having a list which is reused in other webpage so i included it in one file and require the same in other webpage where required
I want to make them active for example if MY RESUME IS CLICKED THE li of myresume become active instead of dashboard so i implement jquery in the same file
but everytime i click on other link other than dashboard the active class is only present in Dashboard l . Is it due to because every time I am going to other page the active class is present on dashboard or due to jquery code(i have included cdn of jquery)??
$(document).ready(function() {
$("li").click(function() {
// remove classes from all
$("li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
});
.active {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="active"><i class="ti-dashboard"></i>Dashboard</li>
<li><i class="ti-wallet"></i>My Resume</li>
<li><i class="ti-wallet"></i>Browse Jobs</li>
<li><i class="ti-wallet"></i>Assessment</li>
<li><i class="ti-hand-point-right"></i>Applied Jobs</li>
</ul>
If you want the active to stay, you COULD use sessionStorage, but why not just ajax the page
https://plungjan.name/SO/ajaxnav/index.html
$(document).ready(function() {
$("#nav a").on("click", function(e) {
e.preventDefault();
// remove classes from all
$("#nav li").removeClass("active");
// add class to the one we clicked
$(this).closest("li").addClass("active");
$("#content").load(this.href);
}).eq(0).click();
});
.active {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="nav">
<li class="active"><i class="ti-dashboard"></i>Dashboard</li>
<li><i class="ti-wallet"></i>My Resume</li>
<li><i class="ti-wallet"></i>Browse Jobs</li>
<li><i class="ti-wallet"></i>Assessment</li>
<li><i class="ti-hand-point-right"></i>Applied Jobs</li>
</ul>
<div id="content"></div>
I have two simple function on click in my page with js, first is to change css active in current li and the other is to reload content only .
change active li
$(".list li").on("click", function(){
$(".list li").removeClass('active');
$(this).addClass('active');
});
reload content only
$('.content').load('Passtel/dashboard');
$('ul.list li a').click(function(){
var page = $(this).attr('href');
$('.content').load('Passtel/'+page);
return false;
});
the problem is, it just function reload content only works if there two are running, but I've tested each of function works as it is.
How can I make both of function works together?
this is my content structure
<!-- Menu -->
<div class="menu">
<ul class="list">
<li class="active">
<a href="dashboard">
<i class="material-icons">home</i>
<span>DASHBOARD</span>
</a>
</li>
<li>
<a href="check">
<i class="material-icons">text_fields</i>
<span>CHECK SITE</span>
</a>
</li>
<li>
<a href="datek">
<i class="material-icons">layers</i>
<span>DATA TEKNIS</span>
</a>
</li>
</ul>
</div>
You can accomplish that with only one function. Hope it helps!
jsbin.com
const ul = $(".list");
const list = ul.find('li');
ul.on("click", 'li a', function(e){
e.preventDefault();
list.removeClass('active');
$(this).parent().addClass('active');
var page = $(this).attr('href');
// replace this with your $('.content').load('Passtel/'+page);
$('.content').load('https://jgatjens.com/?' + page);
});
You can use something like this:
$(function () {
$('.content').load('Passtel/dashboard');
$('ul.list li a').click(function () {
e.preventDefault();
$(".list li").removeClass('active');
$(this).parent().addClass('active'); //added parent() here
var page = $(this).attr('href');
$('.content').load('Passtel/' + page);
return false;
});
});
//$('.content').load('Passtel/dashboard');
$('ul.list li a').click(function (e) {
e.preventDefault();
$(".list li").removeClass('active');
$(this).parent().addClass('active');
var page = $(this).attr('href');
//$('.content').load('Passtel/' + page);
return false;
});
.active {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="menu">
<ul class="list">
<li class="active">
<a href="dashboard">
<i class="material-icons">home</i>
<span>DASHBOARD</span>
</a>
</li>
<li>
<a href="check">
<i class="material-icons">text_fields</i>
<span>CHECK SITE</span>
</a>
</li>
<li>
<a href="datek">
<i class="material-icons">layers</i>
<span>DATA TEKNIS</span>
</a>
</li>
</ul>
</div>
I'm trying to add "active" class to menu when user clicks on the button but for some reason it's not working correctly. They have to click really fast and two times. I've tried both click and on click function but still not working.
$('#menu li').click(function() {
$('#menu li.active').removeClass('active');
$(this).addClass('active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right" id="menu">
<li class="nav active">Home
</li>
<li class="nav">About
</li>
<li class="nav">Services
</li>
<li class="nav">Gallery
</li>
<li class="nav">Contact
</li>
</ul>
</div>
you must handle active li after page loaded.Add this at the end of your code:
var curruntLocation = window.location.href;
$('#menu li a').each(function ()
{
var thisHref = $(this).attr('href');
if (curruntLocation.indexOf(thisHref) > 0)
{
$(this).parent().addClass('active');
}
});
The links included in the menu items are reloading the page while clicking and when the page is reloaded, the initial setting comes first. You can use preventDefault() if you'd like to run the function but then, your links won't work.
I suggest you use anchors instead of query string.
! Latest I've tried. I put it in my head.php which I just include. I'll send over my files if you'd want to see them personally.
Directory of my folder
Main_Folder
-Main_files
-- JS_Folder
---- Js Files
-- Includes_Folder
---- Head.php is here
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
//alert($('ul a').length);
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
}
//alert(this.href);
});
});
</script>
Whole sidebar:
<div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul class="sidebar-menu">
<li class="sub-menu">
<a class="" href="panel-admin.php">
<i class="icon-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-briefcase"></i>
<span>Employees</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-book"></i>
<span>Students</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-calendar"></i>
<span>Scheduling</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
<li><a class="" href="admin-esl.php">ESL Local</a></li>
<li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-pencil"></i>
<span>Enroll</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="general.html">Foreign Languages</a></li>
<li><a class="" href="button.html">ESL Local</a></li>
<li><a class="" href="slider.html">Summer Workshops</a></li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
class="sub-menu" is needed to make it dropdown menus drop. So the active version is class="sub-menu active". In case of a 2 level dropdown menu, both the main bar and sub bar are to be set to active.
This is my side bar.
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li>
<i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li>
<i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
I've tried the following below but none works on my case:
Update class attribute based on page URL
https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/
First sample code
$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu
var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)
if($(this).prop("href") == pagename){
$('.menu li').removeClass("active"); // remove all active class
$(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
}
});
In the first one, I've changed the menu to collapse navbar-collapse navbar-ex1-collapse and collapse only but neither works.
In the second sample code, I've tried doing the following:
$(function() {
$('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
});
I put [2] since I'm currently in the localhost. So it would be localhost/folder_name/index.php.
I also tried putting "/index.php"/ but when I click that it directs me to localhost/index.php instead of localhost/folder_here/index.php.
Third sample code
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
Still doesn't work. I've change $('ul a) to $('div ul a) and $('div li ul a).
EDIT: Just to be sure, the script created is just included by include('js/js_file.js');. This line should be before or after the html is loaded?
As suggested by David Thomas I've tried the following below. But it doesn't work.
var url = 'window.location.pathname';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (url.endsWith(pageAndFile)) {
$(this).closest('li').addClass('sub-menu active');
}
});
One approach:
// obviously, use 'document.location'/'window.location' in the real thing:
var fakeLocation = 'http://www.example.com/index.php';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (fakeLocation.endsWith(pageAndFile)) {
$(this).closest('li').addClass('active');
}
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
For those browsers that don't implement String.prototype.endsWith():
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
// creates a regular expression from the passed-in string, followed by the '$'
// character which signifies that the passed-in string must be followed by the
// end-of-string:
var reg = new RegExp(testString + '$');
// using RegExp.prototype.test() to test that the String we're testing,
// the 'this,' is matched by the created regular expression:
return reg.test(this);
};
var fakeLocation = 'http://www.example.com/index.php';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (fakeLocation.endsWith(pageAndFile)) {
$(this).closest('li').addClass('active');
}
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
And, without jQuery, you could do much the same:
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
var reg = new RegExp(testString + '$');
return reg.test(this);
};
// again, in real-world non-demo use you should use 'document.location':
var fakeLocation = 'http://www.example.com/index.php',
// finding the last portion of the fakeLocation variable:
currentPage = fakeLocation.split('/').pop(),
// getting all the a elements with an href attribute that ends
// with the currentPage string (after escaping the special
// characters with the (ugly) regular expression) and the
// attribute-ends-with ('attribute$=value') selector:
activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']');
// using Array.prototype.forEach to iterate over the array-like
// activeAElements NodeList:
Array.prototype.forEach.call(activeAElements, function(a) {
// the first argument of the function is the array-element,
// here an <a> element node;
// we're adding the 'active' class-name to the parentNode of any <a>
// element that was found by the above selector:
a.parentNode.classList.add('active');
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
As to why your own attempts failed:
$('.menu li a').each(function(){
var pagename= location.pathname.split('/').pop();
// the HTMLAnchorElement.href is the absolute URL formed
// by the href attribute; to find the actual string from
// an <a> element, you'd need to use either JavaScript:
// - this.getAttribute('href');
// or jQuery's:
// - $(this).attr('href');
if($(this).prop("href") == pagename){
$('.menu li').removeClass("active");
$(this).parent("li").addClass("active");
}
});
Your second attempt:
$(function() {
// this won't work because your JavaScript will return 'index.php',
// and pass that into the attribute selector; unfortunately this
// includes the period ('.'), which is a special character in CSS
// and has to be double escaped, first for the JavaScript and then
// the CSS
$('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
// with that in mind, you'd need to do (something like) the following,
// which - as in my own code - replaces all special characters with
// a double-escaped version of that character (so '.' becomes '\\.'):
$('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active');
});
Your third attempt:
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
Looks like it should work, albeit you're adding (or should be adding) the 'active' class-name to the <a> element, rather than the ancestor <li> element.
References:
JavaScript:
Array.prototype.forEach().
Array.prototype.pop().
document.querySelectorAll().
Element.classList API.
Element.getAttribute().
Function.prototype.call().
Guide to regular expressions in JavaScript.
Node.parentNode.
String.prototype.endsWith().
new RegExp() Regular Expression constructor.
RegExp.prototype.test().
String.prototype.split().
jQuery:
addClass().
attr().
each().
prop().
Assuming location.pathname.split("/")[2] returns the expected parameter, the problem is
$('nav a[href^="/'
should be
$('.nav a[href^="'
.nav is a class, not an element, in your example
problem in your script......
$(function() {
$('.nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');t
});