How to stay the Jquery function when the page is reload - javascript

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.

Related

menu close on click on body page

i have created a dropdown menu which opens on clicking the nav button. But i couldn't find a way to close the dropdown menu when the mouse clicks on the body of the page.
I you can figure it out, please help me
(function(){
var bodyEl = $('body'),
navToggleBtn= bodyEl.find('.nav-toggle-btn');
navToggleBtn.on('click', function(e){
bodyEl.toggleClass('active-nav');
e.preventDefault();
});
})();
active-nav is created within css and linked with menu and body
You can bind click event to body, then check if the event is generated from a particular element using event.target
var bodyEl = $('body');
navToggleBtn = bodyEl.find('.nav-toggle-btn');
$('body').on('click', function (e) {
if ($(e.target).hasClass("nav-toggle-btn")) {
bodyEl.toggleClass('active-nav');
e.preventDefault();
e.stopPropagation();
}
else
{
//close the menu here
}
});
I don't know if it is the right solution, but I would add a div element that covers the entire page.
The menu is on top of that div, but the rest is below. If you click the div, it closes itself and the menu.
So basically, it's a lightbox (as for showing images), but without the shade. Or width a shade, because it will make your menu stand out a little more, and it will fit the expectations of disabling clicks on specific elements in the body.
Another advantage of having an extra element instead of just capturing clicks on the main level on the body, it that it won't interfere with other event handlers on the body itself, which could capture the click and therefor have unexpected results for someone who just wants to close the menu.
A rough example can be found below:
$('header > ul > li').on('click', function() {
// Deactive all menu items
$('ul.active').removeClass('active');
// Activate the one clicked.
$(this).closest('li').addClass('active');
// If there is no lightbox setup a new one.
var box = $('.lightbox');
if (box.length == 0) {
// It's just a div with a class.
$('<div>')
.prependTo($('body'))
.addClass('lightbox')
.on('click', function() {
// Lightbox clicked? Remove it, and deactivate the menu.
$('.lightbox').remove();
$('li.active').removeClass('active');
});
}
});
li {
padding: 1em;
}
header > ul > li {
display: inline-block;
vertical-align: top;
position: relative;
background-color: #eee;
}
li > ul {
display: none;
background-color: #ddd;
position: absolute;
top: 100%;
left: 0;
}
li.active > ul {
display: block;
}
.lightbox {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0, 0.2); /* Just for show */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
Header, page title
<ul>
<li>Main
<ul>
<li>sub</li>
<li>sub</li>
<li>sub</li>
<li>sub</li>
</ul>
</li>
<li>Other</li>
<li>About</li>
</ul>
</header>
<section>
Main content
</section>

Make navigations items change color when active

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

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