jquery Current Nav item selector - javascript

I can't figure out how to use jQuery to style the current nav item. I've tried several tutorials and such to no avail. Any help would be appreciated.
Thanks in advance.
<div id="menu">
<ul id="nav">
<li>Contact</li>
<li>Gallery</li>
<li>Pool Liners</li>
<li>Services</li>
<li>About</li>
<li>Home</li>
</ul><!--end nav-->
</div><!--end menu-->
/** nav styling **/
//<![CDATA[
jQuery(function() {
jQuery('#nav li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).addClass('current');
}
});
});
//]]>

You can use the Attribute Equals Selector [name="value"] to find out the nav item with the current path.
$(document).ready(function () {
var str = location.href.toLowerCase();
var item = $('#nav li a[href="' + str + '"]');
if(item.length){
$("li.current").removeClass("current");
item.parent().addClass("current");
}
})
Demo: Fiddle

I figured it out!! Thanks for your help Will.i.am and Arun.p.
THe lines of code below is all I needed after giving body id's to each page.
/** nav selector **/
var bodyid = $('body').attr('id');
$('#main_nav ul li a.'+ bodyid).addClass('current');

Related

JQuery - How to add class to certain span if href equals something

I have a menu on a page. I want to add the class username to the my username span, that has an a href; that equals ?m=user_admin&p=edit_user&user_id=1.
Keep in mind that I want it to add this class, no matter what the username is! because the username will change all the time. How can I do it?
Example of the Menu
<div class="menu">
<ul>
<li><a class="user_menu_link_selected" href="#"><span>Dashboard</span></a></li>
<li><a class="user_menu_link" href="#"><span>Monitor</span></a><li>
<li><a class="user_menu_link" href="#"><span>Admin</span></a></li>
<li><a class="user_menu_link" href="#"><span>FTP</span></a></li>
<li><a class="user_menu_link" href="?m=user_admin&p=edit_user&user_id=1"><span>my username</span></a></li>
</ul>
</div>
I tried this JS code but it added the class to all the spans. I only want it added on the my username span because the href equals ?m=user_admin&p=edit_user&user_id=1.
$('ul a').each(
function(){
if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
$('.menu > ul > li > a > span').addClass("username");
}
});
$('ul a').each(
function(){
if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
$(this).find('span').addClass("username");
}
});
The following line should refer to this:
$('.menu > ul > li > a > span').addClass("username");
Probably
$(this).addClass("username");
use CSS here is the documentation it will select all the span whose parent a has the link
a[href='?m=user_admin&p=edit_user&user_id=1'] span {
color:Red
}
demo - http://jsfiddle.net/zq0fs7om/
Try this..
$('ul li a').each(
function(index){
if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
$(this).children('span').addClass("username");
}
});
You can check out the jsfiddle here:
http://jsfiddle.net/ow1478rd/
here's the gist of the code:
$('ul > li > a').each(function(){
if($(this).attr('href')=="?m=user_admin&p=edit_user&user_id=1"){
$(this).closest("li").find("span").addClass("username");
}
});
Basically the thing to note here is "closest" will basically search UP the DOM, and then "find" will search DOWN the DOM. so with your structure you're going up to the closest list element, and then finding the span inside of it to change the CSS. Hope this helps man.

Using jQuery.ScrollTo to scroll down when a link is clicked

I have a link on top of my page Categories
when this is clicked, the page jumps to the bottom where the target div is located
I am trying to use jQuery.ScrollTo but its not working. I am not sure how to debug.
$(document).ready(function()
{
// Scroll the content inside the #scroll-container div
$('.categories_link').scrollTo({
target:'#categories'
});
});
UPDATE:
Found this http://jsfiddle.net/VPzxG/ so now trying to modify it. Any help would be appreciated.
You don't need JS at all. Just use
<a class="categories_link" href="#categories">Click me!</a>
DEMO: http://jsfiddle.net/ezCFC/
First, I recommend changing the HTML to the following:
<div id="sidebar">
<ul>
<li>auck</li>
<li>Projects</li>
<li>Resume</li>
<li>Contact</li>
</ul>
</div>
then just use .animate() and .offset():
$(function(){
$("#sidebar > ul > li > a").click(function(e) {
e.preventDefault();
var id = $(this).attr("href");
$('body').animate({
scrollTop: $(id).offset().top
}, 1000);
});
});
DEMO:
http://jsfiddle.net/dirtyd77/VPzxG/1465/

Select random list item and add class

At the moment I have an unordered list with the id of menu and one list item within this ul has a class of "selected"
what i would like to do is grab all the list items from within the ul and remove the inital selected class from the list item it is on then assign it to a different list item within the same ul each time the page is refreshed.
Is this possible? Whats the best method to achieve this?
$(document).ready(function() {
var $ulLen = $('#menu li').length;
$('#menu li').removeClass('selected'); // Remove the class
// Select random li..
var rand = Math.floor( (Math.random()* $ulLen ) ); // Select a random li..
$('#menu li:eq('+ rand + ')').addClass('selected');
// Add the selected class to randomly selected li...
});
Check FIDDLE
http://jsfiddle.net/eWbqa/8/
var menu = document.getElementById('menu');
var tags = menu.getElementsByTagName('li');
tags[Math.floor(Math.random() * tags.length)].setAttribute('class', 'selected');
You could expand on that, but that will do it.
*Edited to reflect Naveen's good advice.
This could probably be written shorter, but I wanted it more verbose so you could see the steps. Technically this could pick the same one twice. If you wanted, you could use LocalStorage or a cookie to remember the last item and not select it again. I went for simple.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
//remove the selected class from the li that has it
$("li.selected").removeClass("selected");
//get all the LIs
var menuItems = $("ul#menu li");
//How many do we have?
var numItems = menuItems.length;
console.log(numItems);
//Pick one by randm
var selected = Math.floor(Math.random()*numItems);
console.log(selected);
//And set it
$("ul#menu li:nth-child("+(selected+1)+")").addClass("selected");
});
</script>
<style>
li.selected { background-color: red; }
</style>
</head>
<body>
<ul id="menu">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li class="selected">Item four</li>
<li>Item five</li>
</ul>
</body>
</html>

Add/Remove classes and using Cookie to remember selection

I have this simply piece of JQuery that toggle a class on anchor tags/links.
What I don't know is how do I make the class toggle or add/remove when the other links are clicked? Example: The class can only apply to the link that is click and cannot be on more than one at a time. That's where I am stuck. Well, I don't know how to do it.
Secondly how do I use the JQuery Cookie to keep the currently link active. I have downloaded the cookie extension.
Here is what I have done:
HTML:
<ul class="navbar">
<li>Link1</li>
<li>Link2</li>
<li>Link3</li>
</ul>
CSS:
.activeLink{
color: #930;
}
JQuery:
$(document).ready(function() {
$('.navbar li a').click(function(){
$(this).toggleClass('activeLink');
});
});
Thank you!!
Below is a solution that uses event propagation:
$(function() {
var $activeLink,
activeLinkHref = $.cookie('activeLinkHref'),
activeClass = 'activeLink';
$('.navbar').on('click', 'a', function() {
$activeLink && $activeLink.removeClass(activeClass);
$activeLink = $(this).addClass(activeClass);
$.cookie('activeLinkHref', $activeLink.attr('href'));
});
// If a cookie is found, activate the related link.
if (activeLinkHref)
$('.navbar a[href="' + activeLinkHref + '"]').click();
});​
Here's a demo (without the cookie functionality as JSFiddle lacks support).
Here is how I do it. It's a little simplistic, but it gets the job done without a lot of brain strain.
<ul class="navbar">
<li>Link1</li>
<li>Link2</li>
<li>Link3</li>
</ul>
<script>
$(document).ready(function() {
$('.navbar li a').click(function(){
$('.navbar li a').css('color', 'black');
$(this).css('color', '#930');
});
});
</script>

jQuery .hover() is driving me crazy

I have a project that uses drop-down menus that are nested ul's, like so:
<ul id="nav">
<li id="thome" class="navtab">
HOME
<ul id="subnav_home" class="submenu">
<li>Dashboard</li>
<li>SMS</li>
<li>Email</li>
<li>Twitter</li>
</ul>
</li>
</ul>
Using jQuery, I've added a .hover() to the .navtab li that .show()s the .submenu ul. The problem is that when the cursor moves into the new ul, the .hover()-out for the .navtab fires, .hide()ing the sub-menu, despite the fact that I have the height of the li so that it entirely wraps the .submenu ul.
I've tried adding a delay to the .hide(), but if you pass your cursor over the navtab bar quickly, you get all of the sub-menus at once.
Any solutions for me? Here's the relevant JavaScript. The hide() function is identical to .show() except that it shrinks the height and hides the ul (obviously).
$('.navtab').hover(
function(){
tabShowSubnav($(this).attr('id'));
},
function(){
tabHideSubnav($(this).attr('id'));
});
function tabShowSubnav(menu){
var sb = '#' + menu + ' > .submenu';
var tb = '#' + menu;
$('.navtab').each(function(){
if (!$(this).hasClass('current_page')){
$(tb).addClass('nav_hover');
}
});
$(tb).css('height','239px');
$(sb).show();
}
$('.navtab').hover(
function() {
$(this).children(".submenu").show().children('current_page').addClass("nav_hover");
},
function() {
});
$(".submenu").mouseout(function(){
$(this).hide();
});
$('.navtab').hover(
function() {
$(this).children(".submenu").show().children('.current_page').addClass("nav_hover");
},
function() {
$(this).children(".submenu").hide();
});
This worked for me.
I finally had to go with the jQuery plugin hoverIntent, that ignores children for the purpose of mouseout.

Categories