So basically I'm trying to give a class "current" to highlight the menu item for the current page.
I've tried a couple of snippets I've seen on this website but most of them didn't work. This code is almost working for me, but the problem is although the current menu item is properly highlighted, Home button is also highlighted no matter which page I'm viewing. So like if I'm viewing "Archive" page, both Archive and Home are highlighted.
I'm using Wordpress to build the website by the way and I'm aware that Wordpress supports this effect but I'd like to achieve this without it.
HTML
<ul class="navigation">
<li>Home</li>
<li>Archive</li>
<li>About</li>
</ul>
JS
jQuery(function($) {
$('.navigation li a').each(function() {
var target = $(this).attr('href');
if(location.href.match(target)) {
$(this).addClass('current');
} else {
$(this).removeClass('current');
}
});
});
I'm not really familiar with javascript so there might be some errors.
Thank you for reading this, and have a great new year.
The suggestion of wp_nav_menu is the correct way in WordPress, but if you're just looking for a quick solution and the menu won't change that often, you can get by with a check inside of each list item.
<ul class="navigation">
<li>Home</li>
<li>Archive</li>
<li>About</li>
</ul>
This makes use of WordPress' "Conditional Tags" which effectively come back as "true" or "false" for a given page. Note that the second link checks multiple blog/post conditions (assuming that that is for the blog).
I'm not sure this is help you or not.
If you are using wordpress you can use this for your menu:
<?php
wp_nav_menu(array(
'theme_location' => 'header',
'menu_class' => 'navbar-nav px-0',
'depth' => 2,
'container' => false,
));
?>
and wordpress automatically add aria-current="page" to your 'nav-link' when you landing on current page.
then you can add css to attribute current page like this
ul.navbar-nav [aria-current]:not([aria-current="false"])
Also if you have 'sub-menu' wordpress add '.sub-menu' class to ul child and you can add css like this for 'sub-menu'.
ul.navbar-nav li ul.sub-menu [aria-current]:not([aria-current="false"])
this is my last website you can check it: http://kimiaroz.com/
You can use simple filter
add_filter('nav_menu_link_attributes', 'add_current_class_to_link', 10, 4);
function add_current_class_to_link($atts, $item, $args, $depth)
{
$atts['class'] = $item->current ? 'current' : '';
return $atts;
}
Related
Hi, I'm having real trouble trying to solve this problem of mine. Although in my last 6-7 hours of despair I have come up with several viable options to make the problem go away, I haven't by any means been able to figure it out. I am trying to edit some source code (included) to achieve what the Title of this question suggests.
I am using the following jQuery plugin: jQuery Cycle Plugin - Pager Demo with Prev/Next Controls
What I am trying to get this to do with my own markup is generate the links that contain the <a> elements within the <li> elements come after and before the first and last <li> elements contained in the targeted parent element...(<ul>). Here's the plugins configuration:
$(function() {
$('.recent_slider').cycle({
fx: 'scrollHorz',
timeout: 0,
prev: '.slide_l',
next: '.slide_r',
pager: '.slide_nav',
pagerAnchorBuilder: pagerFactory
});
function pagerFactory(idx, slide) {
var s = idx > 4 ? ' style="display:none"' : '';
return '<li'+s+'>'+idx+'</li>';
};
});
Where pager: '.slide_nav', refers to the parent <ul> element, I have this plugin's next and previous controls being used as <li></li> (with slide_l meaning "slide left" / previous) and <li></li> (meaning "slide right" / next).
What I want to be able to do is insert the pager links generated from return <li'+s+'>'+idx+'</li> in between .slide_l and .slide_r so it appears something like:
<ul class="slide_nav">
<li></li>
<li'+s+'>'+idx+'</li>
<li'+s+'>'+idx+'</li>
<li'+s+'>'+idx+'</li>
<li></li>
</ul>
The issue is that is adds them after so in effect I get something along the lines of "previous","next", "slide1", "slide2", "slide 3" where as what I need is "previous","slide1", "slide2", "slide3", "next"...
Here's the plugin's almighty 1500+ lines of source code which together with the above configuration and markup containing the class names: .slide_nav, .slide_l and slide_rwill cause the headache I'm having...
Please help.
Since you want to change how the UI is displayed, and not the structure of the content, CSS would be a better way to solve this.
Change your html to this:
<span class="slide_l">Prev</span>
<ul class="slide_nav"></ul>
<span class="slide_r">Next</span>
And add this CSS (note this is just a starting point, add onto it to make it look nice):
.slide_nav, .slide_nav li, .slide_l, .slide_r {
display: inline-block;
margin: 0;
padding: 0;
}
The CSS makes all the elements flow horizontally (using display: inline-block) to make it similar to a standard paginator.
Fiddle: http://jsfiddle.net/dwx1v9c7/1/
You could also get the html of the .slide_nav and then mess with it as a string.
var x = $('.slide_nav').html();
var arr=x.split('</li>');
var mystr = '';
for (var r=0, len=arr.length; r<len; r++) {
mystr += arr[r];
if (r===0) {
//your code to add additional LI's
}
}
$('.slide_nav').html(mystr)
It's far from the most elegant solution but it should work.
I'm using blade template, the template contains a navigation bar. it is something like this
<ul>
<li class="active">page1</li>
<li>page1</li>
<li>page1</li>
</ul>
Using jquery I can make the li element active once clicked.
Now the problem is when I click on the second link the page2 will be loaded and that page extends the same template so it will load it again and there then the 1st element will be active. The solution that I thought about is adding a div to each page to let me identify the page
<div class="type" data-type="page2"></div>
and when the page is loaded I set the selected li element depending on the page type.
I try this and it is working the only thing is that I don't think it is the perfect solution. Is there an other more simple way to solve this?
Thanks
I'd set a class on the html element to identity your page. That way you can have javascript as well as css react to what type of page you're on. Not that you need css in this particular example, but down the line use-cases might pop-up and then you already have a solution in place.
edit:
Adding class dynamically through a tiny script:
//script in specific page
<script>pagetype = "page2"</script>
//script as part of layout template shared between pages
<script>
$(function(){
$("html").addClass(pagetype);
})
</script>
In my opinion, a better solution would be detecting the current page with Request::segment() (or Request::is(), depending on the stucture of your URLs) method. Combine that with a View composer to avoid passing data to each view manually.
An example:
The view composer:
class PageComposer
{
public function compose($view)
{
$view->with('active', Request::segment(1));
}
}
The service provider:
class PageServiceProvider extends ServiceProvider
{
public function register()
{
View::composer('partials.header', 'PageComposer');
}
}
The part of the header file that is common to all your pages:
<ul id='pages'>
<li id='page1'>page1</li>
<li id='page2'>page2</li>
<li id='page3'>page3</li>
</ul>
The script that changes the active class:
<script>
$(document).ready(function () {
var activeLink = $('#{{ $active }}');
activeLink.addClass('active');
});
</script>
More information about this in Laravel 4 documentation:
Requests
View Composers
You can compare anchor href to pathname and then add style or assign class to correct anchor e.g
...
<li>Link</li>
...
$('a[href="'+window.location.pathname.split('/').pop()+'"]').css({ color: 'red' });
or
$('a[href="'+window.location.pathname.split('/').pop()+'"]').addClass('current');
How to highlight every link in main menu with a different color based on its current page ?
for example change the contact us link color to red in the main menu when the current page is contact us
and change the about us link color to orange in the main menu when the current page is about us and so on
You can use javascript to do this:
first, retrieve your current url path:
var pathname = window.location.pathname;
for example, return "/contact.html"
then you can use this value to detemine which item to be hilighted:
if(pathname == "/contact.html"){
document.getElementById("contact").addClass("hilighted");
}
and so on.
a:active : when you click on the link and hold it.
a:visited : when the link has already been visited.
If you want the link corresponding to current page to be highlighted, you can define some specific style to the link -
.current {
color: red;
background-color: #000000;
}
Add this new class .current only to the corresponding li (link), either on server-side or on client-side (using javascript/jquery).
With JQuery you could use the .each function to iterate through the linkswith the following code:
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("current");
}
});
});
Depending on your page structure and used links, you may have to narrow down the selection of links like:
$("nav [href]").each ...
if you are using url parameters, it may be necessary to strip these:
if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
This way you don't have to edit each page.
source
There are a lot of approaches, it's hard to say which is best without seeing your code.
You could use some Javascript on each page to add or change the class of your links.
For instance on your contact us page use a a script like
var contactLink = document.getElementById("contactUs");
contactLink.addClass("orangeLink");
You can add active class to the menu based on current page.
if you are in contact page then add active class to contact us menu, same for about us page, then do some css for that active class.
for example if you are in contact-us page then :-
<ul>
<li class="home">Home</li>
<li class="contact active">Contact Us</li>
<li class="about">About Us</li>
</ul>
Now do some css for that :-
.contact.active{
color : red;
}
.about.active{
color : orange;
}
It will worked for you.
<ul>
<li><a onClick="showsub('activ')" class="activ">activ</a></li>
<li>.........</li>
</ul>
(option1-selected) option2 option3 ... ...
option1 (option2-selected) option3 ........
The above, is been used by bootstrap, so when the user click on one of each li
it will be active and it will "selected and looks different than the others".
I have the above code, there is two ways to Make this work.
First, it to add a class="Active" using javascript ... or to remove class="" nothing
which will return it to its original
The second way, is to add data-toggle="pill"
<li><a onClick="showsub('activ')" data-toggle="pill">activ</a></li>
Thus, bootstrap whatsoever javascript will make this work automatically. if you just add
data-toggle="pill" then you don't have to add any javascript..
my problem is;
How can I call specific li? and have the data-toggle="pill" works?
for example..
say you have the following
menue
home info contact
(home) (info) (contact)
news articles others about bio admin feedback
my problem, is I want when I click info, to show bio
or when I click home, to show news without clicking news to show information.
I have done this, by using two functions.
first function to call home,info, contact..
then.
if onClick = home
call function show(news):
elif onClick =info
call function show(bio):
this works fine, but it will sometimes looks like this ...
news (articles) others
news contents ... bla bla bla
notice that, articles is selected, but news (contents) are shown instead.
I hope you get the point..
I want when I call show(news) to be able to use data-toggle="pill"
if onClick = home
call function show(news):
& also pill (news) if it is not pill
so the when I call home, news will appear and also it active on the menue
(home active)
(news active) article other
news contents
Try this way
JS CODE:
$('ul li a').removeClass('active');
$('ul li a').eq(<index of the menu which needs to be loaded>).addClass('active');
Note: this may not be the final Solution, its just a prototype of what could become a final solution.
Happy Coding :)
I have several javascript generated sub menus, which are displayed when a certain word is found in the current url.
I need to set a li tag to li class="active" so that the user can see which submenu page they are currently browsing.
I've found a variety of codes which seem to be relevant, but I can't seem to make any work! The below works perfectly to generate the sub menus though :)
If it helps I'm using the twitter bootsrap for design purposes, for some reason the css file has alot of arrows inserted, eg. .tabs > li
I don't really understand what the > has been inserted for, but could that be causing some kind of a problem perhaps?
Any help much appreciated!
var currenturl = location.pathname
if (currenturl.search(/welcome/i) >= 0)
{
document.write(<ul class="tabs">
<li>Home</li>
<li>Contacts</li>
<li><a href="user_manual.php" User Manual</a></li>
<li>Support & Help</li>
<li>Logout</li>
</ul>);
}
Ok Here's an update!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Wow thanks very much for the reply. I have added the code inside a javascript declaration before the closing body tag as mentioned, though on the welcome.php page I do not see any sub menu having been generated.
In response to the other comment, what I would like to achieve is generating a sub menu based upon the current pages URL.
If the URL contains "support" I would like it to load a certain menu, if "sales" I would like it to load another.
An example sub menu, the one I want to appear when "sales" is detected in the URL is as follows:
<ul class="tabs">
<li>Contacts</li>
<li><a href="sales-user_manual.php" User Manual</a></li>
<li>Support & Help</li>
<li>Something Else</li>
</ul>
To make the current sub menu active I have to further set an li tag active as such:
<li class="active">
This means I will need another piece of code to detect the end of the URL string eg. if the current page open is sales-contact_us.php then the li tag for that menu item is set active.
Thanks!
You should definitely not use document.write to append elements to the document. Use DOM methods instead, eg
var menu = [
{ "label": "Home", "href": "welcome.php" },
{ "label": "Contacts", "href": "contact_us.php" }
// etc
];
var list = document.createElement("ul");
list.setAttribute("class", "tabs");
for (var i = 0; i < menu.length; i++) {
var label = menu[i].label;
var href = menu[i].href;
var item = document.createElement("li");
var anchor = document.createElement("a");
anchor.appendChild(document.createTextNode(label));
anchor.setAttribute("href", href);
if (href == currentUrl) {
item.setAttribute("class", "active");
}
item.appendChild(anchor);
list.appendChild(item);
}
document.body.appendChild(list); // you may want to append the list to another container
Place the above in a script block at the end of your document (right before the closing </body> tag) to ensure the document has loaded before attempting to manipulate it.