Hi I am looking for a solution to add a class to every list item <li> which has a child item with a class of <span class="separator"> and a different class to <li> with an anchor link.
I use Joomla and the menu is being generated somewhat like this:
<ul class="menu">
<li class="item1"><span>Home</span></li>
<li class="parent item59"><span class="separator"><span>Demo</span></span></li>
<li class="item62"><span>Article</span></li>
<li id="current" class="parent active item27"><span>CMS</span>
<ul>
<li class="item50"><span>The News</span></li>
<li class="item48"><span>Web Links</span></li>
<li class="item65"><span class="separator"><span /></span></li>
<li class="item49"><span>News Feeds</span></li>
<li class="item66"><span class="separator"><span /></span></li>
<li class="item67"><span class="separator"><span /></span></li>
<li class="item68"><span class="separator"><span /></span></li>
</ul>
</li>
<li class="item71"><span class="separator"><span>Help</span></span></li>
</ul>
What I want is to add class "anclink" or "seplink" to the <li> depending on their child item so that the final output looks like below.
<ul class="menu">
<li class="item1 anclink"><span>Home</span></li>
<li class="parent item59 seplink"><span class="separator"><span>Demo</span></span></li>
<li class="item62 anclink"><span>Article</span></li>
<li id="current" class="parent active item27" anclink><span>CMS</span>
<ul>
<li class="item50 anclink"><span>The News</span></li>
<li class="item48 anclink"><span>Web Links</span></li>
<li class="item65 seplink"><span class="separator"><span /></span></li>
<li class="item49 anclink"><span>News Feeds</span></li>
<li class="item66 seplink"><span class="separator"><span /></span></li>
<li class="item67 seplink"><span class="separator"><span /></span></li>
<li class="item68 seplink"><span class="separator"><span /></span></li>
</ul>
</li>
<li class="item71 seplink"><span class="separator"><span>Help</span></span></li>
</ul>
How can I achieve this using PHP or even a jQuery solution will be fine.
Kindly help.
With jQuery:
$('#menu > li:has( > span.separator )').addClass('seplink');
$('#menu > li:has( > a )').addClass('anclink');
or:
$('#menu > li > span.separator').parent().addClass('seplink');
$('#menu > li > a').parent().addClass('anclink');
EDIT: I was just walking out the door when I left this solution, so I didn't have the chance to note that I'd strongly favor the second solution since it utilizes a valid CSS selector.
It will perform better in browsers that support querySelectorAll.
Without jQuery:
var ul = document.getElementsByClassName("menu");
var li = ul[0].getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ){
var class = li[i].className;
class += ( li[i].childNodes[0].tagName.toUpperCase() == 'A' ) ? ' anclink' : ' seplink';
li[i].className = class;
}
Edit
So you can eitheir use getElementsByClassName as defined in http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ or use another method such as getElementsByTagName (in your case the root of your nested list is the first UL.
For testing purpose I'd advise you to paste this code in the HEAD of your HTML document. Also, you need to call this function once the window is loaded as you want to apply changes on the window's loaded elements.
<script type="text/javascript">
window.onload = function(){
var ul = document.getElementsByTagName("ul")[0];
var li = ul.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ){
var myClass = li[i].className;
myClass += ( li[i].childNodes[0].tagName.toUpperCase() == 'A' ) ? ' anclink' : ' seplink';
li[i].className = myClass;
}
};
</script>
Adding a second answer, because I'd advise against loading the entire jQuery library if this is its only purpose.
An alternative would be to use Sizzle, which is the CSS selector engine that is included in jQuery. It is a much smaller download, and as such, may be a decent compromise.
You'd get the library, and use it like this:
var li_span = Sizzle('#menu > li > span.separator'),
li_a = Sizzle('#menu > li > a'),
s = li_span.length,
a = li_a.length;
while( s-- ) {
if( li_span[ s ].className === 'separator' ) {
li_span[ s ].parentNode.className += ' seplink';
}
}
while( a-- ) {
li_a[ a ].parentNode.className += ' anclink';
}
The downloaded file is full size, so you'll want to minify it.
Hey #Patrick and #Nabab none of the solutions worked for me but some how managed to work around with this script and it is working fine in even in IE 6-9 and Firefox. I didnt get chance to check on Opera, Chrome and Safari will try it later.
$(document).ready(function() {
$('ul.menu li:not(:has(li))')
.addClass(function() {
return (
($('span.separator',this).length)
? 'seplink' : (($('a[href]',this).length)
? 'anclink' : null));
});
});
This script was contributed by some generous member yesterday here as an answer to this question. I couldn't get his / her name but don't know why later it disappeared from the list of answers. Luckily I had already copied it by then. I am posting this as an answer as it is working perfectly for me.
I am anyway using the entire jQuery library because there are other aspects of my template which need it. Kindly advise if you guys see any challenge which I may not know, in using this script.
Related
I have this:
<ul class="nav navbar-nav">
<li>Link1</li>
<li>Link2 </li>
<li>Link3</li>
<li>Link4</li>
</ul>
I want to add active class so user knows on what page he is at.
My best idea is to have li items with unique id and in jquery check if id=1 to set "Link1" with active class.
Even tho this works, I can't stop wondering if there is a better solution, more elegant one?
If you have php there,as in your tag, you can compare $_GET values. Something like that:
<li <?=$_GET['order_by']=='new' ? 'class="active"' : '';?>>
<a>link</a>
</li>
I would do it server side like cssBlaster21895 has shown, but you can do it client-side with javascript, too.
var links = document.getElementsByClassName('nav')[0].getElementsByTagName('a'),
qString = window.location.search;
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (qString == link.getAttribute('href')) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
}
<ul class="nav navbar-nav">
<li>Link1</li>
<li>Link2 </li>
<li>Link3</li>
<li>Link4</li>
</ul>
I'm still new to Front End Development and working on my first really big site / wordpress blog.
So my question is this, I have a Menu that will be the same on all pages on the site. However each section will have it's name highlighted in the Menu Nav.
Current Nav_Bar markup:
<div id="nav_bar">
<ul class="nav">
<li class="nav_li">Home</li>
<li class="nav_li">About</li>
<li class="nav_li selected">Blog</li>
<li class="nav_li">Book</li>
<li class="nav_li">Media</li>
<li class="nav_li">Events</li>
<li class="nav_li">Services</li>
<li class="nav_li">Contact</li>
<li class="search">
<input type="text" onfocus="if(this.value == 'Search') { this.value = ''; }" value="Search" />
</li>
<li class="search_btn">
<div class="search_button">Go</div>
</li>
</ul>
</div><!-- nav_bar -->
Now I've build pages before using this simple PHP code: <?php include("menu.php"); ?>
However, how would you guys 1st: organize this menu to accept and incoming value, like menu.php+select="home" and 2nd how would you pass in that value to add a class of selected to one of the Menu items?
First off your class on li "nav_li" is redundant and could be removed. Use .nav li in place to ref these list items with less lines of code. This works both as a JQuery selector and CSS selector. Second, to answer you actual question; I would use the active class as follows:
// Assuming the following html. <ul class="nav"><li>About</li></ul>
$('.nav li').click(function() {
$('.nav li.active').removeClass('.active');
$(this).addClass('.active');
window.location = $(this).children('a').attr('href');
return;
});
Now in the area where you keep your navbar you check to see if the current url is active by the following:
<?php
$currentUri = $_SERVER['REQUEST_URI'];
<ul class="nav">
<li class="<?php if($currentUri == '/about.php') {echo 'active';} ?>">About</li>
</ul>
Add the condition in the php script to each list item.
Sincerely,
Kevin
I assume you want your 'incoming value' for the purpose of highlighting a menu item (rather than displaying a particular page)? It's unnecessary, because the browser already knows what page it's on.
This is one way of highlighting the current page in jQuery:
$('.nav li a').each(function(){
var link = $(this).attr('href'),
current_page = location.href;
if(current_page.indexOf(link) != -1) {
$(this).addClass('current-page');
}
});
Before the include, set a value in some parameter, like $page = 'blog' and then in the menu.php
<li class="nav_li<?php echo $page === 'blog' ? " selected='selected'" : "" ?>">Blog</li>
This can be done using javascript
var url=document.location.toString();
if(url=="http://www.something.com/some.php")
{
//code to add class to specific link
}
else if(url=="http://www.something.com/someelse.php")
{
//code to add class to specific link
}
You can also do this on server side in menu.php
$url=$_SERVER['REQUEST_URI']
Then check the url and add class name accordingly
If I'm understainding what you're after, maybe something like:
index.php:
<?php
$page = 'home';
// page code ...
?>
about.php:
<?php
$page = 'about';
// page code ...
?>
etc, etc...
Then menu.php tweaked slightly:
<div id="nav_bar">
<ul class="nav">
<li class="nav_li home">Home</li>
<li class="nav_li about">About</li>
<li class="nav_li blog">Blog</li>
<li class="nav_li book">Book</li>
<li class="nav_li media">Media</li>
<li class="nav_li events">Events</li>
<li class="nav_li services">Services</li>
<li class="nav_li contact">Contact</li>
<li class="search">
<input type="text" onfocus="if(this.value == 'Search') { this.value = ''; }" value="Search" />
</li>
<li class="search_btn">
<div class="search_button">Go</div>
</li>
</ul>
</div><!-- nav_bar -->
and finally some javascript:
<script>
$(function () {
$('#nav_bar li.<?=$page?>').addClass('selected');
});
</script>
That assumes jQuery is being used, but it isn't necessary obviously, the same could be done with straight javascript.
Why does this jquery not slide toggle my php generated list?
I've tried changing a couple of things to get this to work and none worked.
EX: $('ol>li:has(ol)').click $(this).children('ol').slideToggle(); $(this).siblings('ol').slideToggle();
PHP:
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol class="list_hold">';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li class="list">'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</li>';
}
}
echo '</ol>';
}
Jquery:
$(document).ready(function(){
$('ol ol').slideUp();
$('ol>li').click(function(){
$(this).next('ol').slideToggle();
});
});
HTML example:
<ol>
<li class="list">find_folders
<ol class="list_hold" style="display: none; ">
<li class="list">Thumbs.db</li>
<li class="list">find.css</li>
<li class="list">find.php</li>
<li class="list">index.php</li>
<li class="list">minus.png</li>
<li class="list">plus.png</li>
<li class="list">test folder
<ol class="list_hold" style="display: none; ">
<li class="list">bananas</li>
</ol>
</li>
</ol>
</li>
</ol>
Based on your supplied html, you'll need to do something like this:
$('li:has(ol)').each(function () {
$(this).children('ol').slideUp();
$(this).on("click", function (event) {
event.stopPropagation();
$(this).children('ol').slideToggle();
});
});
http://jsfiddle.net/farneman/n2Arc/2
The main issue is that your selectors were not correct with your actual html.
Try this:
$(document).ready(function(){
$('ol ol').slideUp();
$('ol>li').on("click", function(){
$(this).next('ol').slideToggle();
});
});
on works for dynamically generated content, such as what is created by PHP's echo. The echoed elements aren't present on the page when you add the click handler to them; that's why your click event isn't working.
Can't see from your PHP what your HTML looks like but you might need something like this?
$('ol>li').live("click", function(){
$(this).parent().next('ol').slideToggle();
});
Assuming that your HTML looks something like this:
<ol>
<li> </li>
</ol>
<ol>
<li> </li>
</ol>
The issue is that this refers to the element clicked (the <li> in this case), which in your case doesn't have an <ol> siblings. You need the sibling of the parent of the <li>, the next <ol>.
Might want to try this:
$('ol ol').slideUp();
$('ol>li').click(function(e) {
e.stopPropagation();
$(this).children('ol').slideToggle();
});
You're using .next() which works on sibling elements but your ordered lists are actually children of the parent lists. In that case you'd want to use a selector like find() or children().
jsFiddle example.
I currently have this:
jQuery:
jQuery(document).ready( function(){
var thispage = location.pathname.substring(1);
//document.write(thispage);
jQuery('#menu li a[href~="'+ thispage + '"]') // ~= is contains. Tweak as needed.
.addClass('active');
});
CSS:
li.active {
background-color: yellow;
}
HTML:
<nav id="topNav">
<ul id="menu">
<li>HOME</li>
<li>ABOUT US</li>
<li> TECHNOLOGY</li>
<li>CAREERS
<li>BLOG
<!--<ul>
<li style="background-color:#898486;">OPPORTUNITIES</li>
</ul>-->
<li class="last">CONTACT US</li>
</ul>
</nav>
My goal is to each menu item to shade a different color when the page is active. I have tried numerous ways to fix this but I am unable to get this to work. in my CSS i even have an element item for :focus, but it only works when the href="#" and not with my current setup. What am I doing wrong here?
Got it to work with two changes:
jQuery('#menu li a[href*="'+ thispage + '"]').parent().addClass('active');
As I suggested in my comment use *= as "contains", not ~= ("contains word"), and I think you wanted to add the active class to the <li/>, not the <a/> tag.
echo $nav gives code like this:
<ul>
<li class="someclass">sometext
<ul>
<li class="someclass">sometext</li>
<li class="spacer"></li>
<li class="someclass">sometext</li>
<li class="spacer"></li>
<li class="someclass">sometext</li>
<li class="spacer"></li>
<li class="someclass">sometext</li>
<li class="spacer"></li>
</ul>
</li>
<li class="spacer"></li>
<li class="someclass">sometext</li>
<li class="spacer"></li>
</ul>
There are list items with class spacer inside each child ul, after each normal list item.
How do I remove the spacer list items which are grandchildren of the main list, using PHP?
Example: <ul> <li> <ul> <li class="spacer">
I'm searching for a regular expression, which should erase <li class="spacer"></li> only in a child <ul> element.
If you don't have access to the $nav variable to remove it (which you likely do) then I'd just use CSS to hide it, something like this should work:
li ul li.spacer {
display:none;
}
If however you have access to $nav - delete that spacer li from the code. Simples.
Also, on a side note. having empty elements like that on the page as "spacers" is semantically bad. This should be handled via CSS, add margins/padding on other elements on the page, don't use a class of spacer, if you do then you may as well go back to using stray <br /> tags everywhere to create spaces.
$xml = new SimpleXMLElement($nav);
$spacers = $xml->xpath('li//li[#class="spacer"]');
foreach($spacers as $i => $n) {
unset($spacers[$i][0]);
}
echo $xml->asXML();
This is converting to XML (use a recent PHP 5.3 version and DOMDocument to export to HTML). Output:
<?xml version="1.0"?>
<ul>
<li class="someclass">sometext
<ul>
<li class="someclass">sometext</li>
<li class="someclass">sometext</li>
<li class="someclass">sometext</li>
<li class="someclass">sometext</li>
</ul>
</li>
<li class="spacer"/>
<li class="someclass">sometext</li>
<li class="spacer"/>
</ul>
How about str_replace?
$nav = str_replace('<li class="spacer"></li>','',$nav);
edited code below
Based on the new requirement this code works. I know its hacky and sloppy but it works:
$temp = explode("\n",$nav);
for ($i=0;$i<count($temp);$i++) {
if (strstr($temp[$i],"<ul>")) {
$nested_ul = 1;
}
if (strstr($temp[$i],"</ul>")) {
$nested_ul = 0;
}
if ($nested_ul==0) {
if (!strstr($temp[$i],"spacer")) {
$new_nav .= $temp[$i]."\n";
}
} else {
$new_nav .= $temp[$i]."\n";
}
}
echo $new_nav;
"Easily" is relative. It depends on a few things. If you want, modify where the $nav is getting generated from.
use preg_replace to replace the li tags:
$new_nav = preg_replace('/<li class="spacer"></li>/', '', $nav);
echo $nav;
There are multiple ways:
Do not create it. It will be easier if you do not create something you do not want. It will be easier to maintain. So if you have any control over what is generated into $var string, just change it.
Simply replace it like that: str_replace('<li class="spacer"></li>', $var).
Use some HTML parser and remove the nodes.
Use JavaScript to remove <li class="spacer"></li> on client side.
Use substr_replace and strpos instead of str_replace, and specify an offset just after the first spacer.
http://www.php.net/manual/en/function.substr-replace.php
http://www.php.net/manual/en/function.strpos.php
Add the following CSS
ul ul li.spacer { display: none; }
Try this:
$nav = str_replace('<li class="spacer"></li>', '', $nav);