On one page, alphabet.php, in my project I have a sidebar further down on the page that loads diverse php-pages in a Content div. Like this:
HTML SideMenu
<nav id="sideMenu">
<ul class="list-unstyled components">
<li id="a">A</li>
<li id="b">B</li>
<li id="c">C <span class="caret"></span>
<ul>
<li id="c1">C1</li>
<li id="c2">C2</li>
</ul>
</li>
</ul>
</nav>
<div id="Content">
<h2>Lorem bla bla</h2>
<p>lorem bla bla </p>
</div>
JS
$(function() {
'use strict';
var newHash = '',
$content = $("#Content");
$("#sideMenu").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function() {
newHash = window.location.hash.substring(1);
$content.load(newHash);
console.log(newHash);
});
});
The same content should be loaded also when you click the topmenu and footer navigation. And at the same time scroll to the Content div.
HTML MainMenu
<li class="dropdown"><a href="#alpha" class="dropdown-toggle" data-
toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
Alphabet <span class="caret"></span></a>
<ul class="dropdown-menu dropdown-menu-left" role="menu" id="alpha">
<li>A
</li>
<li>B
</li>
<li>C
<ul class="dropdown-menu dropdown-menu-left" role="menu">
<li>C1</li>
<li>C2</li>
</ul>
</li>
</ul>
</li>
I solved the JS for the main-menu with this code
$(function() {
'use strict';
if(location.hash) $('#Content').load(location.hash.substring(1));
$('#alphaa').click(function() {
$('#Content').load(this.hash.substring(1));
});
});
EDIT: I changed the URL in MainMenu to alphabet.php#a.php etc., and it loads the content into the div IF you are on the current page (alphabet.php). Not if you're on another page.
EDIT 2: Solution for the main-menu JS. Now everything works fine but I guess you could make it prettier without two different js functions for the main-menu and the side-menu, but for now I'm pleased with this. It works!
Here is how i am able to do the navigation
i wrote the links like:
<a class="nav-link" href="javascript:void(0);" data-href="/page1.html #div1">Page 1</a>
<a class="nav-link" href="javascript:void(0);" data-href="/page2.html #div2">Page 2</a>
<a class="nav-link" href="javascript:void(0);" data-href="/page3.html #div3">Page 3</a>
If you use javascript:void(0) in your href= then you don't need to call the event.preventDefault.
then in my scripting side i wrote:
$(window).on('load', function () {
$('.nav-link').on('click', function () {
var linkPage = $(this).attr('data-href');
if (linkPage !== undefined)
{
$('#content').load(linkPage);
}
});});
Note
One thing you need to make sure is that domain of the calling page and pages from which the data has to come should be the same or else you will have the cross-domain issue.
Edit 1
The #div1,#div2,.#div3 are basically the ids of the div on their respective pages from which the data has to be fetched.
for example if i have some content on my pages like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Page 1</title>
</head>
<body>
<div id="div1">
hi i am the content of page 1
</div>
</body>
</html>
So, when someone clicks on the menu links the load function will go to the particular page (which is in our case the page1.html or any other) and return the HTML contents of div with id as div1 and load the data to the particular div(i.e. div with id content).
Edit 2
The JQuery's Load() is better explained on this Jquery Load you can use this to understand more about it.
So, what i think you are doing is you are creating a request to a /page1.html from the domain www.example.com, in that case load function will call the www.example.com/page.html and will load the contents of the page but if you make a request to other any other page let say /page11.html from the domain www.example.com/page2.html then the load() will create this www.example.com/page2.html/page11.html url which is not correct and hence it will not load any content.
So,what you can do is either you can put the whole url on the of the page i.e. www.yourdomain.com/page.html #divid in the attribute data-href or you can create the particular url on the javascript calling funciton like:
$(window).on('load', function () {
$('.nav-link').on('click', function () {
var linkPage = $(this).attr('data-href');
if (linkPage !== undefined)
{
var pageUrl = window.location.origin+'any other seperation for the pages
if any'+linkPage;
$('#content').load(pageUrl);
}
});
});
Here the window.location.origin is going to give you the domain on which the website is running regardless of hashes or slashes and then it will concate it with the linkPage and will make the proper url for the called page.
I have the the following in my script tag. However, whenever I click the on test.php or test2.php li links, I am not redirected to the respective pages.
However, the active class changes from the index.php file to the test.php or test2.php file depending on which link has been clicked but I am not directed to the page. I attempted to the solutions in the following links, but now of them produce the desired result that I want, which is to redirect me to the page clicked and update the active class to the li element.
How to change active class while click to another link in bootstrap use jquery?
Active link after click
Whenever I uncomment this line e.preventDefault(), I am able to navigate to the link that have been click but the active class is not updated to the the
li elememnt clicked, but when the said line is commented, I am not able to navigate to the page clicked, instead, the active class is updated on the li element clicked.
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="active">
<a href="index.php">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li class="">
<a href="test.php">
<i class="material-icons">group</i>
<span>Test</span>
</a>
</li>
<li class="">
<a href="test2.php">
<i class="material-icons">people</i>
<span>Test2</span>
</a>
</li>
</ul>
</div>
And the script code:
$(document).ready(function () {
$('.menu .list a').click(function(e) {
$('.menu li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
The contents of test.php are as follows:
<body class="theme-red">
<nav class="navbar">
<?php include_once('navbar.html'); ?>
</nav>
<section>
<aside id="leftsidebar" class="sidebar">
<?php include_once('left-side-bar.html');?>
</aside>
</section>
<section class="content">
<div class="container-fluid">
<div class="row clearfix">
<table id="tbl-users" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</tfoot>
<tbody>
<?php
$accounts = get_details();
foreach($accounts as $acc){
?>
<tr>
<td><?php echo $acc['id']; ?></td>
<td><?php echo $acc['name']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</section>
</body>
Why is the problem arising?
The problem arises that, when you use e.preventDefault() on click of
anchor tag, the default behaviour is to redirect the page and that's
why the page doesn't load but the active class gets added. But when
you don't use e.preventDefault(), the page redirects immediately
and the change you did happen but before it was redirected and not
for the new page(which could be redirected current page or some other page), that's why you can't see the class active added to
it.
.
How to fix the problem?
Well, there are a couple of ways to go about it. I'd say that from the
test.php or test2.php return a value, which you can validate against
the javascript with if-else conditions, if the value matches you make
that li class as active.
Here's the changes you need to make:
Add a span on each of your pages to which you have hyperlinked i.e test.php, test2.php, etc. having text the same as your hyperlink in the anchor tag so for test.php add a span as:
<span id="curpage" style="display:none;">test.php</span>
Then, add a script at the end of your body tag (you may be able to add this script in a seperate file and include in all of your php files using <?php include(".."); ?> :
$('a[href=\"' + $("#curpage").text() + '\"]').parent().addClass("active");
Here's a sample code, that you can try and implement. Make 2 files in
the same directory named as a.html having the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<span id="curpage" style="display:none;">a.html</span>
<div class="menu">
<li>1</li>
<li>2</li>
</div>
<script>
$('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>
And b.html having the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<span id="curpage" style="display:none;">b.html</span>
<div class="menu">
<li>1</li>
<li>2</li>
</div>
<script>
$('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>
And now when you change the pages by clicking the link, you can see
how the color of bullet changes.
I don't think you should be changing the "active" class just when the li links are clicked. Think that when you redirect your users to a specific page from another, the li links "OnClick" event won't be fired at all, hence, the active menu link won't be displayed appropriately.
Now, what I usually do to solve this issue (don't know if it's the most elegant solution, but it works) is to place a tag at the top of each html content template (I'm assuming you're using templates for the Header, Footer and Content here), I give it a descriptive ID, like "page-name" or "section", and add a data attribute to it with the name of the menu link that this page "belongs" to:
<div id="page-name" data-page="home-page">
Then with JQuery you can ask for the div's data like this:
var current_page = $("#page-name").data("page");
And simply alter the menu links class depending on what page the user is currently in:
// remove the "active" class from ALL the links first
$(".menu li a").removeClass("active");
if (current_page === "home-page") {
// add the "active" class just to the link you want
$("#home-page-link").addClass("active")
}
Of course, you would do that with a switch and you would have to load the js file on ALL pages (that's why the use of the Header template is so important, since you would just need to include it once). Also, in the html "data-page" attribute, the "page" part can be anything, just remember to call it appropriately later.
Hope I helped.
To dynamically add a class, on page load, to the navigation item of the current page, consider:
Checking the current page url: $(location).attr('href') OR
$(location).attr('pathname')
Looping through anchor elements (a) of the navigation menu to
determine if any of the href attribute values match the current
page url with a conditional check using the .indexOf() method:
if(anchorEl.indexOf(currentPageUrl) >= 0)
If any do, add the required class, using the .addClass() method:
$(this).addClass('current');
Code Snippet Demonstration:
Note: Intended for the sake of demonstration
The code snippet embedded below uses specific urls to provide a working example and to demonstrate the intended functionality. Adjust accordingly to apply to a given production environment.
$(document).ready(function () {
var currentPageUrl = $(location).attr('href'), // store current page url in variable
anchorEl;
$('.menu a').each(function(){
anchorEl = $(this).attr('href'); // store href atribute of current anchor element in iteration
console.log('anchor link url:',anchorEl);
console.log('current url of window:',currentPageUrl);
if(anchorEl.indexOf(currentPageUrl) >= 0) { // if anchor element contains
$(this).addClass('current');
console.log('class "current" was added.');
}
});
});
/*
Note:
$(location).attr('href') = full absolute path (https://stacksnippets.net/js)
$(location).attr('pathname') = relative path (/js)
*/
.current {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<ul class="list">
<li>
<a href="https://stacksnippets.net/foobar1">
<span>foobar #1</span>
</a>
</li>
<li>
<a href="https://stacksnippets.net/foobar2">
<span>foobar #2</span>
</a>
</li>
<li>
<a href="https://stacksnippets.net/js">
<span>This should be the <em>current</em> url</span>
</a>
</li>
</ul>
</div>
You should know e.preventDefault() will prevent default behavior of that object which called on it (redirect in this case). So you are preventing your application from redirect to that href you specified.
You can change your function code like this:
$(document).ready(function () {
$('.menu .list a').click(function(e) {
$('.menu li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
//Here is needed change
location.href = $(this).attr('href');
});
});
Edit 1:
So you can work like this approach:
1) Specify a class name for each li tag
2) Send the class name that must has active class after redirection and page load
3) Read the passed class name from url and add/remove to/from your li tags
So your html code will be as following:
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="home active">
<a href="index.php">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li class="group">
<a href="test.php">
<i class="material-icons">group</i>
<span>Test</span>
</a>
</li>
<li class="people">
<a href="test2.php">
<i class="material-icons">people</i>
<span>Test2</span>
</a>
</li>
</ul>
</div>
If you need to script code according to this solution which I explained, so I will update my answer.
Edit 2:
You need to have below script codes in your file:
function setActiveClass() {
//Remove active class from all li tags
$('.menu li.active').removeClass('active');
//Find current url
var url = $(location).attr('href');
if (url.contains("activeClass")) {
//Find the index of active class in url
var start = url.indexOf("#activeClass");
//Add 6 unit to start index because of the longest class name is people which has 6 character
var end = start + 6;
//Fetch passed class name from url
var className = url.substring(start, end);
//Add active class corresponding to passed class name
if(className.contains("home"))
$(".home").addClass('active');
else if(className.contains("group"))
$(".group").addClass('active');
else
$(".people").addClass('active');
} else {
//Add active class for default mode (when we have not any redirect yet)
$("#defaultLiTag").addClass('active');
}
}
$(document).ready(function () {
//Call the function
setActiveClass();
$('.menu .list a').click(function(e) {
e.preventDefault();
var classNameOfParent = $(this).parent().attr('class');
var classNameToBePassedByUrl = "home";
if(classNameOfParent.contains("group"))
classNameToBePassedByUrl = "group";
else if(classNameOfParent.contains("people"))
classNameToBePassedByUrl = "people";
location.href = $(this).attr('href') + "#activeClass=" + classNameToBePassedByUrl;
});
});
i had the same problem after a lot of searching i could find this solution in this link i hope it could help you. Although you should remove class active and add class active to clicked navbar item ,you should use location.href to add active class when the new page reload.
https://santosh-shah.com/add-class-active-page-refresh-jquery/
I have a JS Fiddle of what I want to do and it's almost there. https://jsfiddle.net/Fm6bR/1/
But what I want to do is have the content load when the URL is clicked from an email for example.
e.g. www.mocksite.co.uk/#A will load the content in A
www.mocksite.co.uk/#B will load the content in B etc.
When I run this on my test site I can see that the anchor tag is selecting the option just not displaying any of the content below it.
<span class="link">A</span>
<span class="link">B</span>
<span class="link">C</span>
<div class="test-listing-container">
<ul class="test-full-list">
<ul class="test-category-list">
<a name="A"></a>
<div class="anchor-header">- A -</div>
<li id="test-list-A">
Some Link 1 - A
Some Link 1 - A
</li>
</ul>
<ul class="test-category-list">
<a name="B"></a>
<div class="anchor-header">- B -</div>
<li id="test-list-B">
Some Link 1 - B
Some Link 1 - B
</li>
</ul>
<ul class="test-category-list">
<a name="C"></a>
<div class="anchor-header">- C -</div>
<li id="test-list-C">
Some Link 1 - C
Some Link 1 - C
</li>
</ul>
</ul>
</div>
<script>
$.noConflict();
jQuery(document).ready(function(){
jQuery('ul.test-category-list').hide();
jQuery(document).on('click', '.link a', function (evt) {
var $a = jQuery(evt.currentTarget),
name = $a.attr('href').substr(1),
$a2 = jQuery('.test-listing-container').find('a[name="' + name + '"]'),
$ul = $a2.parents('ul.test-category-list').first();
jQuery('ul.test-category-list').hide(); // hide all
$ul.show(); // show the relevant one
});
});
</script>
The above is what I have done so far in the JS fiddle.
Ideally I won't have the 3 links anywhere in the HTML they will all be hidden and just be able to access the content as they have clicked through to the page.
I'm pretty new to javascript so if someone could show me it in a js fiddle and explain a little what they've done then that would be great
thanks in advance
I will keep my question short for the sake of brevity. I have a page (lets say page 1) on which I have 2 links attached to two different anchor tag and on clicking those anchor tag, I am redirecting user to page 2. However I would like to highlight (add class 'active') on two different list element on page 2, which depends whether the user have clicked anchor 1 or 2 from the previous page. As of now the first li tag is highlight with class active.
This is my HTML markup on page 1 where I have anchor tags
<div class="landing-thumb">
<div class="view view-first">
<div class="mask">
<a id="link1" class="info">Click here</a>
</div>
</div>
</div>
<div class="landing-thumb">
<div class="view view-first">
<div class="mask">
<a id="link2" class="info">Click here</a>
</div>
</div>
</div>
JS for on click event
$('#link1').on('click', function () {
window.location = "/page2";
});
$('#link2').on('click', function () {
window.location = "/page2";
});
On page 2, I have a list which is generated dynamically (by default the first element in list has a class 'active') (only the span id is different for every list element). Here is the rough HTML mark up
<ul id="menu" class="nav nav-pills">
<li class="active">
<a href="#">
<span id="spanLink1">List 1</span>
</a>
</li>
<li>
<a href="#">
<span id="spanLink2">List 2</span>
</a>
</li>
<li>
<a href="#">
<span id="spanLink3">List 3</span>
</a>
</li>
<li>
<a href="#">
<span id="spanLink4">List 4</span>
</a>
</li>
</ul>
Now what I am trying to achieve over here if the user click on link1 from page 1, he/she will be redirected to page 2 with li class active which has span id="spanLink3" and on clicking link2 from page 1 li class active which hasspan id="spanLink4"
Add some hash tag into your url
$('#link1').on('click', function () {
window.location = "/page2#link1";
});
$('#link2').on('click', function () {
window.location = "/page2#link2";
});
And on that page get this hash tag
window.location.hash or use php code also and add class accordint to it
I have a navigation menu in a page that highlights the current menu you’re on based on the URL by adding a class.
My problem is that my page is paginated, so sometimes the user will end up at:
http://example.com:4001/wordpress/calientes/page/2/ ,
/page/3/ , /page/4/ and so on...
what’s the best way to keep my menu highlighted while the user is browsing the pages?
This is my menu:
<div class="innerhead">
<ul>
<li> Calientes </li>
<li>Tendencias</li>
</ul>
</div>
This is the Script that i use to highlight the current page menu:
<script>
$(function(){
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".innerhead a").each(function() {
// checks if its the same on the address bar
if(url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
</script>
Another option could be:
<div class="innerhead">
<ul>
<li id="calientes"> Calientes </li>
<li id="tendencias"> Tendencias</li>
</ul>
</div>
In your script:
var url = window.location.pathname.split('/');
$('#'+url[4]).addClass("active");