Make navigations items change color when active - javascript

I have the html code
<header> <nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
</header>
the css code :
a {
color: #7e7e7e;
text-decoration: none;
font-weight: bold;
}
a:hover {
color: #444;
}
a.active {
color: #82b965;
}
nav {
float: right;
padding: 20px;
}
ul {
list-style: none;
}
li {
display: inline-block;
float: left;
padding: 10px
}
.current {
color: #333333;
}
and javascript is:
$(document).ready(function(e) {
$("nav a").on(function(){
$("nav a").removeClass("active");
$(this).addClass("active");
});
});
what I want is that when any button will active that time the color will be green,and other will remain same color.and I want to put them in the middle,and needs to be little big space between them.
the jsfiddle is:
jsfiddle code
I have done this..But not working..

$(document).ready(function(e) {
$("nav a").click(function(){
$("nav a").removeClass("active");
$(this).addClass("active");
});
});
Fiddle:https://jsfiddle.net/130w0y9c/
To make nav links center
Updated Fiddle:https://jsfiddle.net/130w0y9c/1/

there were some small errors. just use click() function if you use jquery anyway.
working fiddle:
https://jsfiddle.net/94b94u1g/

http://codepen.io/anon/pen/QbZdWr Done, working... the main problem was the on click
$(document).ready(function(e) {
$("nav ul li a").on("click", function(){
$("nav ul li a").each(function () {
$(this).removeClass("active");
});
$(this).addClass("active");
});
});

You had two errors:
First, as #Andrew said, Home should be Home.
Secondly, your use of the .on function in jQuery was missing out your target event. $("nav a").on(function(){... should have been $("nav a").on("click", function(){... . Also, if you're going by the codepen, make sure you have jQuery running it.
http://codepen.io/anon/pen/MwPJWZ

Related

Find error: highlight side menu based on page scrolling position

Trying to highlight side menu based on page scrolling position. The nice example is shown here.
However, when practising in a different way, not able to get similar effect for scrolling. Codes are here.
$('#sn').on('click', function(event) {
$(this).parent().find('a').removeClass('active');
$(this).addClass('active');
});
$(window).on('scroll', function() {
$('.target').each(function() {
if($(window).scrollTop() >= $(this).position().top) {
var id = $(this).attr('id');
$('#sn a').removeClass('active');
$('#sn a[href=#'+ id +']').addClass('active');
}
});
});
#sn {
width: 20%;
position: fixed;
}
#sn a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
/* Change the link color on hover */
#sn a:hover {
background-color: #555;
color: white;
}
#sn .active {
background-color: #666;
color: rgb(58, 133, 204);
}
#sn .active:hover {
background-color: #4f5f;
color: rgb(235, 157, 13);
}
section {
height: 100vh;
overflow: auto;
background-color: #F7F7F7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="sn" class="toggle_sn">
About
Education
Social
</ul>
<section class="target" id="abt_sec">
ABOUT
</section>
<section class="target" id="edu_sec">
EDUCATION
</section>
<section class="target" id="soc_sec">
SOCIAL
</section>
What I'm doing wrong? How to debug errors in web designing? Is this jquery version problem (e.g. is in 1.10.1, mine is 3.3.1)?
1) Add class="target" to your sections. Like so:
<section id="abt_sec" class="target">ABOUT</section>
<section id="edu_sec" class="target">EDUCATION</section>
<section id="soc_sec" class="target">SOCIAL</section>
Because jQuery code selects elements with target class $('.target').each(function()
2) Correct last line syntax:
From this:
$('#sn a[href=#'+ id +']').addClass('active');
to this:
$('#sn a[href="#'+ id +'"]').addClass('active');
Because css selector should be in this syntax: #sn a[href="#abt_sec"] instead of: #sn a[href=#abt_sec].
This doesn't work in your case because jQuery v3.3.1, if you change the jQuery version in the working example from jsFiddle from 1.1 to 3.3.1 that one doesn't work either with same error like your example:
Uncaught Error: Syntax error, unrecognized expression: #sn a[href=#abt_sec]
So your code should look like this:
$('#sn').on('click', function(event) {
$(this).parent().find('a').removeClass('active');
$(this).addClass('active');
});
$(window).on('scroll', function() {
$('.target').each(function() {
if($(window).scrollTop() >= $(this).position().top) {
var id = $(this).attr('id');
$('#sn a').removeClass('active');
$('#sn a[href="#'+ id +'"]').addClass('active');
}
});
});
A codepen to see it working: Codepen

How to stay the Jquery function when the page is reload

How can I stay the Jquery functions when it leaves the page?
The code below is running good when the link is blank/#, but When I change the # and make it the path link, the jquery seems not running properly. I click it, it change the background but when it goes to the link the background was gone, is there something I miss in the code?
$(document).ready(function(e){
$('#main-menu li a').click(function(e) {
$('#main-menu li a').removeClass('active');
$(this).addClass('active');
});
});
#main-menu li {
display: inline-block;
font-family: 'Raleway', sans-serif;
padding: 17px 25px;
}
#main-menu li a {
color:#333333;
font-size:15px;
}
#main-menu li.active a {
color:#0198cf;
}
#main-menu li:last-child {
padding-right: 0;
}
.active{
background-color:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="topnav" id="main-menu">
<li ></i> Home</li>
<li></i> Home2</li>
<li></i> Home3</li>
<li></i> Home4</li>
</ul>
Add this script:
$(function () {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('#main-menu li a').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
$(this).parent().previoussibling().find('a').removeClass('active');
}
});
});
You need to stop default behavior of a element. You should call preventDefault function for your a click event:
$(document).ready(function(e){
$('#main-menu li a').click(function(e) {
e.preventDefault();
$('#main-menu li a').removeClass('active');
$(this).addClass('active');
});
});
If the user is traveling off of the current page, the styles modified by jQuery will be gone permanently, as they are not saved anywhere.
However, using javascript you can store cookies, and if that cookie exists, you can add the background style you desire.
See https://www.w3schools.com/js/js_cookies.asp for more insight into storing cookies.

Change color <li>

I'm building a survey and what I'm trying to do now is that when someone clicks an answer (for example: 8) in my list, the background of that answer changes color. This has to work for each seperate answer (there are 60 questions).
The list html/css code:
<div class="answers">
<ul>
<li class="liFirst">1</li>
<li class="liMiddle">2</li>
<li class="liMiddle">3</li>
<li class="liMiddle">4</li>
<li class="liMiddle">5</li>
<li class="liMiddle">6</li>
<li class="liMiddle">7</li>
<li class="liMiddle">8</li>
<li class="liMiddle">9</li>
<li class="liLast">10</li>
</ul>
</div>
.answers {
float: right;
width: 400px;
height: auto;
margin: 0;
background: #DFE5E3;
}
.answers ul {
display: inline-block;
}
.answers li {
float: left;
padding: 0 auto;
font-weight: bold;
}
I've already researched it a bit but can't seem to find a solution that works. I suppose I have to do this in JS/jQuery?
Tried this solution: link! but didn't seem to work for me
add an active class
.active{
background:#000;
color:#FFF;
}
and in jquery toggle class
$('ul li').on('click',function(){
$(this).toggleClass('active');
});
if he wants to choose only one answer
$('ul li').on('click',function(){
$(this).toggleClass('active').siblings().removeClass('active');
});
You can do this with the following:
JQuery
$(document).on('click', '.answers ul li', function(){
$(this).toggleClass('selected').siblings().removeClass('selected');
});
CSS
.answers li.selected {
background: yellow;
}
You probably want to remove the selected background effect one other <li>s once you click on one.
DEMO
If you want to stay strictly CSS based, this checkbox hack may be your best bet... http://css-tricks.com/the-checkbox-hack/
Which can also be implemented with radio buttons to ensure only one answer can be chosen.
jQuery
$( "ul" ).on( "click", "li", function() {
$("li").removeClass("selected");
$(this).addClass("selected");
});
CSS
.selected { background-color:lime;}
JSFiddle Demo

JS Menu keep menu state

I have this HTML Code:
<div id="nav">
<li>Dashboard</li>
<li><a>Contacts</a>
<ul>
<li><strong>Companies</strong></li>
<li>Add Company</li>
<li>View Company</li>
</ul>
</li>
</div>
and this JS:
<script>
$(document).ready(function () {
$('#nav > li > a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
</script>
for my vertical menu but i cant work out how to keep the menu state when the page changes.
for example, if the is expanded, how can i keep it expanded if the page changes?
here is the CSS to:
#nav {
float: left;
margin-left:5px;
margin-top:-20px;
top:0;
left:0;
width: 100%;
list-style:none;
}
#nav li a {
display: block;
padding: 8px 10px;
margin-bottom:0;
background: #666666;
border-top: 1px solid #EEEEEE;
border-bottom: 1px solid #EEEEEE;
text-decoration: none;
color: #EEEEEE;
width:155px;
}
#nav li a:hover, #nav li a.active {
background: #F36F25;
color: #FFFFFF;
cursor:pointer;
}
#nav li ul {
display: none;
list-style:none;
}
#nav li ul li {
margin-top:0;
margin-right:0;
margin-bottom:0;
margin-left:-40px;
}
#nav li ul li a {
background: #EEEEEE;
color:#666666;
border:1px solid #EEEEEE;
}
#nav li ul li a:hover {
background: #EEEEEE;
color:#f36f25;
border:1px solid #f36f25;
}
I would suggest using sessionStorage in this scenario. It's a great tool in this case, and it is widely supported, but see http://caniuse.com/namevalue-storage to see if its suitable for your needs. What you can do is use sessionStorage to keep track (client-side) of your currently expanded menu so you can expand the correct menu on a page reload. This answer is not 100% correct in the sense that you can't just plug it in directly into your code (I would have had to guess at several things) but it should give you a fairly idea of where to go. Note that in the code below, I changed link hrefs to point to JSFiddle because that is where I made a working example, but hopefully this will get you on the right track to implement it in your own pages.
One of the main things necessary to change is to give main menu <a> tags an ID (below, they are menuDashboard and menuContacts). These would have to be consistent across your different pages, and also the scripts below would have to be included in all the pages where you want to keep the menu state. Then the basic premise is that on menu click, we store the currently expanded menu <a> ID into sessionStorage so we can access that after a page reload. Then, on page load, we look at sessionStorage to see what was previously selected by retrieving the key "activeMenuItemID", and if we find that is not undefined, we expand that menu item.
Working example: http://jsfiddle.net/VBLS8/2/show/
Note, because of how JSFiddle is built, the previous link is a link directly to JSFiddle Results iframe is. Otherwise, when clicking the links JSFiddle just breaks. The actual JSFiddle is here: http://jsfiddle.net/VBLS8/2/.
<br/>
<div id="nav">
<li>
<a id="menuDashboard">Dashboard</a>
<ul>
<li><strong>Sub Category</strong></li>
<li>Sample 1</li>
<li>Sample 2</li>
</ul>
</li>
<li>
<a id="menuContacts">Contacts</a>
<ul>
<li><strong>Companies</strong></li>
<li>Add Company</li>
<li>View Company</li>
</ul>
JavaScript:
$(document).ready(function(){
//Loop through nav items, compare to expanded item ID from sessionStorage so we can expand whichever item was previously expanded
if(sessionStorage.getItem("activeMenuItemID") != undefined){
$("#nav > li > a").each(function(){
if ($(this).attr("id") == sessionStorage.getItem("activeMenuItemID")){
expandMenuItem(this);
}
});
}
$('#nav > li > a').click(function(elem){
expandMenuItem(this);
});
});
function expandMenuItem(elem){
if ($(elem).attr('class') != 'active'){
$('#nav li ul').slideUp();
$('#nav > li > a').removeClass("active");
$(elem).addClass("active");
$(elem).next().slideToggle();
sessionStorage.setItem("activeMenuItemID", $(elem).attr("id"));
}
}
When the page changes, the click handler gets bound, but there is no statement handling the initial state of the menu.
So...
$(document).ready(function() {
//original click handler
//$('#nav a').click
//but also this piece of code, that will display all the lists having an .active link inside
$('#nav ul').has('a.active').show();
});
Regards and good luck!
A quick but a little dirty solution to keep track of your currently active page is to compare the src attribute of your target frame with the href attribute of your links.
Edit: The following fiddle might help you a bit: fiddle

Transform CSS { ul li:hover a } in JQUERY .hover

I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.
CSS:
ul li:hover a {
color: #FFF;
}
Can anyone Help ?
EDIT:
My problem is:
I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.
JQuery:
$("ul li").hover(function () {
$(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
$(this).stop().animate({ backgroundColor: "black"}, 400);
});
To animate background color on hover in menu and submenu.
For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)
$('ul.submenu li a').hover(function () {
$(this).css({color:'#FFFFFF'});
}, function () {
$(this).css({color:'#00FF00'});
});
All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.
I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.
HTML Structure:
<ul class="menu">
<li>text</li>
<li>text
<ul class="submenu">
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
<li>text</li>
</ul>
Please let me know if this is along the right track of what you're asking.
I haven't got it working fully, but give this a look and see if it helps:
my JSFiddle
Here's the code so far:
$(document).ready(function() {
var sm; // submenu
var delay = 500; // delay before applying changes
var tID; // timeout id
var color_on = '#fff'
, color_off = '#000';
var oPrev;
$('ul.menu > li > a').hover(
function() {
if (tID && $(this) === oPrev) {clearTimeout(tID);}
oPrev = $(this);
sm = $(this).next('.submenu');
if(sm){sm.stop(true, true).fadeIn('slow');}
},
function() {
if (tID) {clearTimeout(tID);}
tID = setTimeout(
function() {
sm.stop(true, true).fadeOut('slow');
}, delay);
}
);
$('.submenu > li > a').hover(
function() {
if (tID) {clearTimeout(tID);}
oPrev.css('color',color_on);
$(this).stop(true, true).fadeIn('slow');
},
function() {
if (tID) {clearTimeout(tID);}
sm = $(this);
tID = setTimeout(
function() {
oPrev.css('color','');
sm.closest('ul').stop(true, true).fadeOut('slow');
}, delay);
}
);
});
And CSS:
a
{
color : #000;
text-decoration : none;
}
a:hover
{
color : #fff;
}
ul li
{
background : orange;
border : 1px solid black;
display : inline-block;
padding : 0 1em;
vertical-align : top;
}
.menu
{
background : #ccc;
border : 1px solid black;
display : inline-block;
padding : .25em 1em;
vertical-align : top;
}
.submenu
{
border : 1px solid black;
border-width : 1px 0 0 0;
display : none;
}
.submenu li
{
background : red;
border-width : 0;
}
.submenu li a:hover
{
color : #fff;
}
Note: I'm not saying this is the best answer, nor is it a complete solution, but maybe something in here will assist someone in finding the correct solution.
$("ul li a").hover(function() {
$(this)
.data("color", $(this).css("color"))
.css("color", "#FFF");
}, function() {
$(this).css("color", $(this).data("color"));
});
$("ul li").hover(function() {
$(this).find("a")
.data("color", $(this).css("color"))
.css("color", "#FFF");
}, function() {
$(this).find("a").css("color", $(this).data("color"));
});
Update:
Assuming that the first selector (ul li a:hover) is superfluous, we can simplify the code considerably:
$("li").hover(function() {
$(this).find("a").css("color", "#FFF");
}, function() {
$(this).find("a").removeAttr("style");
});
This updated code should work also (under the condition that you don't have additional CSS code inside the style attribute of the ANCHOR elements).
Update:
An alternative solution would be this:
$("li").hover(function() {
$(this).toggleClass("hover", $(this).is(":hover"));
});
with this CSS code:
ul li.hover a {
color: #FFF;
}
I highly recommend this alternative solution!
$('li').hover(
function(){
$(this).css({color:'white'}); //mouseover
},
function(){
$(this).css({color:'black'}); // mouseout
}
);
Try this (now tested: http://jsfiddle.net/nathan/J7HLV/):
$('ul li a, ul li').hover(function () {
$(this).add($(this).children('a')).filter('a').css('color','#fff');
},function () {
$(this).add($(this).children('a')).filter('a').css('color','');
});
Sure, simply use the hover binding.
$("ul li a").bind("hover", function () {
$(this).css("color", "#FFF");
});
$("ul li").bind("hover", function () {
$(this).children("a").css("color", "#FFF");
});
Note that this code won't reset the CSS properties when you mouse out. To do that you would need to store the original color values.
It is probably worth it to set that a element to display: block so it expands to the entire parent li element. Then you only need to hover on one of them.
Bind a hover function for the li tag. Whenever mouseover/mouseout is on the <a> tag the event will bubble up to the <li>
$(function(){
$("ul li").hover(function(){
$(this).css("color", "#fff");
},function(){
$(this).css("color", "#000000");
});
});
See a working demo
If you can achieve the effect using CSS then why go for javascript solution.

Categories