how to dynamically set the active class in bootstrap navbar? - html

I am using bootstrap nav bar with codeigniter as backend.
Now In my application i want to change the < li> class to active dynamically for each page.
So i can known i am on which page currently.
Below is my code:
<ul class="nav navbar-nav">
<li class="active">Dashboard</li>
<li>Company</li>
<li>Users Management</li>
<li>Key Management</li>
<li>Activated Devices</li>
</ul>
<ul class="nav navbar-nav navbar-right">

You can use this javascript to add active class based on current url please try it
<script type="text/javascript">
$(document).ready(function () {
var url = window.location;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
});
</script>

Can't you just use this replacing your <a> tags. This will match the current uri string, with the links href attribute. If it matches, it add's an active class to the link. You can style the .active using you
Company
So the entire code will be.
<ul class="nav navbar-nav">
<li>Dashboard</li>
<li>Company</li>
<li>Users Management</li>
<li>Key Management</li>
<li>Activated Devices</li>
</ul>
<ul class="nav navbar-nav navbar-right">

Your pages should know which menu should be set as active.
Try adding an id to your <li> and add a javascript code to your pages to set the active menu based on the ID.
Example:
<ul class="nav navbar-nav">
<li id="menu-dashboard" class="active">Dashboard</li>
<li id="menu-company">Company</li>
<li id="menu-user">Users Management</li>
<li id="menu-key-management">Key Management</li>
<li id="menu-activation">Activated Devices</li>
</ul>
<script>
var menuid = "menu-dashboard";
$(function() {
$('.nav li').removeClass('active');
$(menuid).addClass("active");
});
</script>
Pages:
Add the following javascript lines to your pages
Company page
menuid = "#menu-company";
User page
menuid = "#menu-user";

You can achieve it by using jQuery or JavaScript.
jQuery example:
$('.nav li').click(function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});

The jQuery in the accepted answer do not know the difference if the visitor is coming from http://example.com or http://example.com/index.php and would not activate the "home" menu-item. This is my fix for that.
HTML This is a snippet from my menu:
<div class='navbar'>
<a href='index.php'><div class='nav-icon icon-home'></div>Hem</a>
<a href='calender.php'><div class='nav-icon icon-calender'></div>Kalender</a>
<a href='exchange.php#utbyte'><div class='nav-icon icon-byte'></div>Byten</a>
</div>
This is a function I've added to my database controller class to find out what protocol the visitor use:
public static function adr_protocol()
{
$str = 'http://';
if(isset($_SERVER['HTTPS']) && 'on' === $_SERVER['HTTPS']) $str = 'https://';
return $str;
}
jQuery:
;var ix = '<?php echo DBController::adr_protocol()."{$_SERVER['HTTP_HOST']}/"; ?>';
var url = (window.location==ix)?window.location+'index.php':window.location;
$('div.navbar a[href="'+ url +'"]').parent().addClass('active');
$('div.navbar a').filter(function() {
return this.href == url;
}).addClass('active');

Related

what can I do to fix my jQuery without any hard-coding in my HTML?

When I checked my work I see undefined in my work. It's not supposed to be there. Can anyone help?
jQuery
$(document).ready(function () {
var listItems = $("#productList li");
listItems.each(function (idx, li) {
var product = $(li);
product.append(" - <b> ("+product.attr('data-type')+") </b>");
});
});
HTML
<ul id="productList">
<li data-activity-type="family">Snow Tubbing</li>
<li data-activity-type="family">Snowcat Mountain Tour</li>
<li data-activity-type="adventure">SnowSlam 11 Racing Course</li>
<li data-activity-type="adventure">Snowboarding</li>
<li data-activity-type="adventure">Edge 11 Performance Ski Racing</li>
<li data-activity-type="family">Dog Sled Tour</li>
<li data-activity-type="family">Snowshoeing</li>
<li data-activity-type="kids">Kid's Night Out</li>
<li data-activity-type="kids">Bear Cub Kamp at the Nursery</li>
</ul>
I'm assuming the activity-type value is going to append to innerHTML.
the data-type should be data-activity-type.
$(document).ready(function () {
var listItems = $("#productList li");
listItems.each((index, item) => {
item = $(item);
item.html( item.html() + `- <b>${ item.attr('data-activity-type') }</b>` );
});
});

How do I load the html pages on a div when I click in a link (using AJAX AND JQUERY)

<div id="menu">
<nav>
<ul class="nav_links">
<li><a id ="homelink" href="#">Home</a></li>
<li><a id="aboutlink" href="#">About</a></li>
<li><a id="locationlink" href="#">Location</a></li>
</ul>
</nav>
</div>
<Main id="main_container">
</Main>
Now I need the AJAX AND JQUERY code that when I click on one of the anchors, the content froM a document. HTML is displayed on main_container.
FOR EXAMPLE: CLICK ON HOME LINK>DISPLAY ON MAIN CONTAINER THE CONTENT FROM HOME
You need to use the jQuery .load() method to load the page URL, and event.preventDefault to prevent redirecting to the page itself, like so:
$('#menu .nav_links a').click(function(e) {
e.preventDefault();
var $this = $(this),
$href = $this.attr('href');
$('#main_container').load($href);
});

How to order a list with nav?

I am attempting to create a way of ordering a list into specific sections using a nav bar. For example, all list items displays under 'All' and then the option to refine the list into 3 other sections.
Current example
https://ibb.co/pvBV4Lf
Does anyone have any suggestions on how to achieve this? Any examples?
I'm not even sure what you would name this kind of function
<div class="nav">
<h1>All</h1>
<h1><span>Residential</span></h1>
<h1><span>Commercial</span></h1>
<h1><span>Retail</span></h1>
</div>
<ul>
<li>Granville Place</li><br>
<li>Palisade</li><br>
<li>King & Phillip</li><br>
<li>Castle Residences</li><br>
<li>Opera Residences</li><br>
<li>Brighton Collection</li><br>
<li>Carpe Group</li><br>
<li>The Lennox</li><br>
<li>South Quarter</li><br>
<li>One Barangaroo</li><br>
<li>One Queensbridge</li><br>
<li>Australia 108</li><br>
<li>Oceans Freshwater</li><br>
<li>The Pavilions</li>
</ul>
Welcome to stackoverflow,
one way to filter your list element is to append a data-* attribute to your elements and bind a javascript function on your links in the div.nav to filter the list:
window.addEventListener('DOMContentLoaded', () => {
// filter list
const filterList = e => {
e.preventDefault();
// fetch filtertype
const type = e.target.closest('a').getAttribute('data-filter-type');
// hide or display list elements
document.querySelectorAll('ul li').forEach(li => {
li.style.display = type === li.getAttribute('data-filter-type') || type === 'all' ? 'list-item' : 'none';
});
};
// bind links
document.querySelectorAll('.nav a').forEach(a => {
a.addEventListener('click', filterList)
});
});
h1 { font-size: 18px; }
<div class="nav">
<h1>All</h1>
<h1><span>Residential</span></h1>
<h1><span>Commercial</span></h1>
<h1><span>Retail</span></h1>
</div>
<ul>
<li data-filter-type="residential">Granville Place</li>
<li data-filter-type="residential">Palisade</li>
<li data-filter-type="commercial">King & Phillip</li>
<li data-filter-type="commercial">Castle Residences</li>
<li data-filter-type="residential">Opera Residences</li>
<li data-filter-type="residential">Brighton Collection</li>
<li data-filter-type="commercial">Carpe Group</li>
<li data-filter-type="retail">The Lennox</li>
<li data-filter-type="retail">South Quarter</li>
<li data-filter-type="residential">One Barangaroo</li>
<li data-filter-type="residential">One Queensbridge</li>
<li data-filter-type="retail">Australia 108</li>
<li data-filter-type="commercial">Oceans Freshwater</li>
<li data-filter-type="commercial">The Pavilions
</ul>

Cant onClick event do <li> tag React

I have a sideBar that opens when I click on a button and i have <li> items there.
I want do add an onCLick event to those items but, onClick event fires when page is loaded and when ever I click on <nav className={drawClass}> elements.
Any information is helpful, thank you.
const Sidedraw = props => {
let drawClass = "sideDraw";
if (props.show) {
drawClass = "sideDraw open";
}
return (
<nav className={drawClass}>
<ul>
<li className="matches" onclick={console.log("work work")}>
Pro matches
</li>
<li className="matches">Public mathes</li>
<li className="matches">Players</li>
<li className="matches">Teams</li>
</ul>
</nav>
);
};
As others have mentioned, the onClick should be a function reference.
Also, you will likely get a warning with the current code:
Non-interactive elements should not be assigned mouse or keyboard event listeners
You should place an interactive element (anchor, button, etc.) within the list item.
<ul>
<li className="matches">
<button onClick={() => console.log('work work')}>Pro matches</button>
</li>
<li className="matches">Public mathes</li>
<li className="matches">Players</li>
<li className="matches">Teams</li>
</ul>
You’re setting the onClick to the result of the console.log call, not the function itself. You want:
onClick={() => console.log("work work")}
Check out the docs for Handling events.
Also, you might want to move your click handler into its own function so that you can easily add it to all nav items.
const Sidedraw = props => {
let drawClass = "sideDraw";
if (props.show) {
drawClass = "sideDraw open";
}
function clickHandler(evt) {
console.log(evt.target)
}
return (
<nav className={drawClass}>
<ul>
<li className="matches" onClick={clickHandler}>Pro matches</li>
<li className="matches" onClick={clickHandler}>Public mathes</li>
<li className="matches" onClick={clickHandler}>Players</li>
<li className="matches" onClick={clickHandler}>Teams</li>
</ul>
</nav>
);
};
Stackblitz
you must add clickeventhandler to each element you want to perform some actions.
<li className="matches" onClick={handleValueChange}>Pro matches</li>
and you must add that function ie
handleValueChange = (e) => {
// ...
}

Changing the Values in an Unordered List <ul> using ng-repeat; also set an active <li>

I have been trying to work out how to produce a list, where if you click on one of the objects in the list, it becomes active. I have managed to get it working in the non-dynamic version of the code with ease. However, working on AngularJS dynamic version, I just can't seem to get it to work. The data is ok, so it can't be data related, it has to be my dynamic code that is not working.
This is a working piece of code (however not dynamic)
<ul class="nav nav-pills" ng-init="catVal = 1">
<li ng-class="{active: catVal===1}">
Category 1
</li>
<li ng-class="{active: catVal===2}">
Category 2
</li>
<li ng-class="{active: catVal===3}">
Category 3
</li>
</ul>
Now What I really want is an AngularJS dynamic version of this code. This is what I have tried and failed so far.
<ul class="nav nav-pills">
<li ng-repeat="category in model" ng-init="catVal = 1" ng-class="active: catVal === category.catID ">
{{category.catName}}
</li>
</ul>
The catID is associated with the category and should give the same results as the previous list. I get the names in the correct place, just the value is not working.
try this.
var app = angular.module("app",[]);
app.controller("ctrl" , function($scope){
$scope.rowIndex = -1;
$scope.items = [{"name":"ali","score":2},{"name":"reza","score":4},{"name":"amir","score":5},{"name":"asd","score":10}];
$scope.selectRow = function(index){
if(index == $scope.rowIndex)
$scope.rowIndex = -1;
else
$scope.rowIndex = index;
}
});
.active{
background-color:#a11af0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">
<ul class="nav nav-pills" ng-init="catVal = 1">
<li ng-repeat="item in items" ng-class="{'active':rowIndex == $index }" ng-click="selectRow($index)">
{{item.name}}
</li>
</ul>
</div>