Adding an active class to menu using jquery problem - javascript

I'm new to Jquery/JS and still learning. I need to add an "active" class to my menu. I know there are already many similar questions across this forum and web as well but nothing works. It had bugged me for days and I still couldn't figure out the problem.
Here is my HTML :
<nav id="nav-menu-container">
<ul class="nav-menu">
<li class="menu-active">Home</li>
<li>About</li>
<li>News</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav><!-- #nav-menu-container -->
Here is my code to add the class:
$('.nav-menu a, #mobile-nav a').on('click', function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
if ($(this).parents('.nav-menu').length) {
$('.nav-menu .menu-active').removeClass('menu-active');
$(this).closest('li').addClass('menu-active');
}
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
$('#mobile-body-overly').fadeOut();
}
return false;
}
});
I'm sorry I didn't explain it in detail before. I want the link menu to be redirecting to another page. The code originally came from a one page-web theme I use, but I customize it to fit my multi-page web application.
Thanks again.

You can do:
$('.nav-menu').on('click', function (e) {
e.preventDefault();
$('.nav-menu .menu-active').removeClass('menu-active');
$(e.target).parent('li').addClass('menu-active');
});
li.menu-active a {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav id="nav-menu-container">
<ul class="nav-menu">
<li class="menu-active">Home</li>
<li>About</li>
<li>News</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav>

<div id="side-bar">
<ul>
<li>Home</li>
<li>Who we are</li>
<li>Services</li>
<li>What to expect</li>
<li>Representative clients</li>
<li>Success stories</li>
<li>Current litigation</li>
<li>What if you could not be a doctor?</li>
</ul>
</div>
script
$(document).ready(function () {
alert(localStorage.getItem("selectedolditem"));
$("#side-bar a").click(function () {
var id = $(this);
$(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", $(id).text());
alert(localStorage.getItem("selectedolditem"));
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$("a:contains('" + selectedolditem + "')").addClass("active");
}
});
css
.active {color:red;}

If you have multiple pages try with this. the below code activate the menu with the current page
when you have like this.
<nav id="nav-menu-container">
<ul class="nav-menu">
<li>Home</li>
<li>About</li>
<li>News</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav><!-- #nav-menu-container -->
<script>
$(function() {
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('menu-active');
});
</script>

Here is how it can work with localStorage.
I am afraid the snippet tool does NOT allow localStorage so you will have to see it working here:
https://repl.it/#PaulThomas1/BraveOffbeatByte
document.addEventListener('DOMContentLoaded', () => {
// try and load
if (localStorage) {
let active = localStorage.getItem('activeMenu');
if (active) document.querySelector(`a[class="${active}"]`).classList.add('active');
}
});
document.addEventListener('click', (e) => {
// try and save
if (e.target.matches('a') && localStorage) {
localStorage.setItem('activeMenu', e.target.className);
}
});
<nav id="nav-menu-container">
<ul class="nav-menu">
<li class="menu-active">Home</li>
<li>About</li>
<li>News</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav>
<!-- #nav-menu-container -->

Related

how to detect click outside of push menu and close menu

I'm using javascript to open a push menu.But, I'd like to add the feature that if the mouse clicks outside of the push menu, it will close the menu. I've never coded this before so really unsure of where to begin.
$(document).ready(function() {
$menuLeft = $('.pushmenu-left');
$nav_list = $('#nav_list');
$nav_list.click(function() {
$(this).toggleClass('active');
$('.pushmenu-push').toggleClass('pushmenu-push-toright');
$menuLeft.toggleClass('pushmenu-open');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="pushmenu pushmenu-left">
<div class="pushmenu_inner">
<ul class="links">
<li>Home</li>
<li>About Us</li>
<li>Missions</li>
<li>Partners</li>
<li>Events</li>
<li>Contact</li>
<li>Give</li>
</ul>
</div>
</nav>
Add event to trigger click operation and follow if it contains your menu or not.
I am giving an example, I hope it will help you with solving your issue. 
html
<nav class="pushmenu pushmenu-left" id='menuBar'>
<div class="pushmenu_inner">
<ul class="links">
<li>Home</li>
<li>About Us</li>
<li>Missions</li>
<li>Partners</li>
<li>Events</li>
<li>Contact</li>
<li>Give</li>
</ul>
</div>
</nav>
Javascript
window.addEventListener('click', function(e){
if (document.getElementById('menuBar').contains(e.target)){
console.log('clicked inside');
// toggle your menu according to your requirements
} else{
// toggle your menu according to your requirements
console.log('clicked outside');
}
});
Use this Jquery
$(document).click(function () {
//Write your code here
});
it means when you are clicked outside that part your respective code will run
Try this. I added an initial style to hide menu. You can then display the menu using the menu button or clicking on the document.
$(document).ready(function() {
$('#menu').click(function() {
if($('nav').is(':visible')) {
hideMenu();
}
else {
$('nav').show(function() {
$(this).animate({left:'0'});
$('#menu').html('hide menu');
});
}
});
$(document).click(function(e) {
if(!$(e.target).closest('#menu').length && $('nav').is(':visible')) {
hideMenu();
}
});
});
function hideMenu() {
$('nav').animate({left:'-100px'}, function() {
$(this).hide();
$('#menu').html('show menu');
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="menu">show menu</button>
<nav class="pushmenu pushmenu-left" style="display:none; left:-100px; position: relative">
<div class="pushmenu_inner">
<ul class="links">
<li>Home</li>
<li>About Us</li>
<li>Missions</li>
<li>Partners</li>
<li>Events</li>
<li>Contact</li>
<li>Give</li>
</ul>
</div>
</nav>

Change background each time onClick function is called

I want to change background each time onClick is called and remove previous tab background, but when I try to do so the previous onClick effect stays
Here is the Code
<script type="text/javascript">
function myFunction() {
document.getElementById("a").style.backgroundColor = "lightblue";
}
</script>
<a href="#home" class="tabs">
<li id="a" onclick="myFunction" class="tabs-li">Home</li>
</a>
<a href="#about-us" class="tabs">
<li id="a" onclick="myFunction" class="tabs-li">About Us</li>
</a>
<a href="#contact-us" class="tabs">
<li id="a" onclick="myFunction" class="tabs-li">Contact Us</li>
</a>
Zeroth Law: An id shouldn't be duplicated.
First, learn HTML. It is annoying for every HTML guy to see non-semantic tags.
You should nest the tags correctly. Hit the person you taught this. Also, the most blundered and ill-fated W3Schools, (NEVER I RECOMMEND), which is hated by everyone also doesn't do this mistake.
Wrong:
<a><li></li></a>
Right:
<li><a></a></li>
Second, the onclick.
You need to add () at the end.
onclick="myFunction()"
Fourthly, you are generalizing.
I have recently seen a lot of developers doing this. Instead, why not just use a simple :hover in CSS, without JavaScript. Let's see without JavaScript:
li:hover {background-color: lightblue;}
<ul>
<li>Home</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
For your way, using JavaScript, using onclick():
$(function () {
$("li").click(function () {
$(this).css("background-color", "lightblue");
});
$("li a").click(function () {
$(this).closest("li").css("background-color", "lightblue");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
Finally, what you need:
$(function () {
$("li").click(function () {
$("li").removeAttr("style");
$(this).css("background-color", "lightblue");
});
$("li a").click(function () {
$("li").removeAttr("style");
$(this).closest("li").css("background-color", "lightblue");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>

When User Open One DropDown Close Other DropDowns

I Want When User Click On One DropDown All Other open DropDown Get Closed . I looked for answer in google but that is not working for my dropdown i know it's simple but i am unable to this pls help me !!
<div class="hh_drop_down">
<ul class="hh_main">
<li class="hh_main_menu">
Chemicals
<ul class="hh_inner">
<li>Additives / Boosters</li>
<li>Anti-Allergen</li>
<li>Concrete</li>
</ul>
</li>
<li class="hh_main_menu" >
<a class="hh_sf" href="#">Equipment</a>
<ul class="hh_inner">
<li>Deodorization</li>
<li>Duct Cleaning Equipment</li>
<li>Hard Surface</li>
</ul>
</li>
<li class="hh_main_menu" >
<a class="hh_sf" href="#">Accessories</a>
<ul class="hh_inner">
<li>Bonnets/Pads</li>
<li>Brush/Rake/Sponge</li>
<li>Carpet Rakes</li>
</ul>
</li>
</ul>
</div>
And jquery i am using in this :
<script>
$(document).ready(function(){
$(".hh_main").on('click' , '.hh_sf' , function(event){
event.preventDefault();
if($(this).next().hasClass('hh_inner')) {
$(this).next().slideToggle();
}
});
});
</script>
Try this:
HTML:
<div class="hh_drop_down">
<ul class="hh_main">
<li class="hh_main_menu">
Chemicals
<ul class="hh_inner expanded">
<li>Additives / Boosters</li>
<li>Anti-Allergen</li>
<li>Concrete</li>
</ul>
</li>
<li class="hh_main_menu">
<a class="hh_sf" href="#">Equipment</a>
<ul class="hh_inner expanded">
<li>Deodorization</li>
<li>Duct Cleaning Equipment</li>
<li>Hard Surface</li>
</ul>
</li>
<li class="hh_main_menu">
<a class="hh_sf" href="#">Accessories</a>
<ul class="hh_inner expanded">
<li>Bonnets/Pads</li>
<li>Brush/Rake/Sponge</li>
<li>Carpet Rakes</li>
</ul>
</li>
</ul>
</div>
JQuery:
<script>
$(document).ready(function () {
$(".hh_sf").next().addClass("collapsed").slideUp();
$(".hh_main").on('click', '.hh_sf', function (event) {
event.preventDefault();
var currentClass = $(this).next().prop('class');
if (currentClass == "hh_inner expanded") {
$(this).next().removeClass("expanded");
$(this).next().addClass("collapsed");
$(this).next().slideUp();
} else {
$(".expanded").slideUp().addClass("collapsed").removeClass("expanded");
$(this).next().removeClass("collapsed");
$(this).next().addClass("expanded");
$(this).next().slideDown();
}
});
});
</script>
JsFiddle
I opened dropmenu with show and hide and made event on li you can use different way
try this :
JQuery :
$(".hh_main_menu").click(
function(){
$(this).next(".hh_inner").toggle();
if($(this).siblings(".hh_main_menu").children(".hh_inner").css("display")=="block")
{
$(this).siblings(".hh_main_menu").children(".hh_inner").hide();
}
} );

What's wrong with this? Load Pages when links are clicked

I am using Ajax for a website I am in the process of developing and something is wrong with this code... When the URL is something like mywebsite.com?about I want the about page to be displayed.
Here is the HTML portion of the code (NOTE: When a link is pressed Text is to be inserted into the DIV 'content'):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="script/open_page.js"></script>
<div id="wrapper">
<div id="header">
<ul class="nav">
<li>Home</li>
<li>About Us</li>
<li>Exchanges</li>
<li>Photos</li>
<li>Contact</li>
</ul>
</div>
<div id="content">
</div>
</div>
Here is a portion of the JavaScript:
var currentpage;
function load_about() { // Loads About Us
if ($current_page == "about") {
$(document).ready(function(){
$("#content").load("contents/about.html");
});
}
}
Thanks for any suggestions or answers...
Since you are calling load_about on click of home page link, I don't think the if condition is necessary. Also the use of dom ready is wrong in this case
It should be
function load_about() { // Loads About Us
$("#content").load("contents/about.html");
}
If it is upto me, I may do it slightly differently
<div id="wrapper">
<div id="header">
<ul class="nav">
<li>Home</li>
<li>About Us</li>
<li>Exchanges</li>
<li>Photos</li>
<li>Contact</li>
</ul>
</div>
<div id="content">
</div>
And
$(document).ready(function(){
$('#header ul.nav li').click(function(){
$("#content").load($(this).find('a').attr('href'));
return false;
})
});
<ul class="nav">
<li>Home</li>
<li>About Us</li>
<li>Exchanges</li>
<li>Photos</li>
<li>Contact</li>
</ul>
$(function() {
$('.nav').on('click', 'a', function(e) {
e.preventDefault();
var pageToLoad = $(this).data('page');
$.get('contents/' + pageToLoad + '.html'), null, function(response) {
$("#content").html(response);
});
});
});

Jquery Dropdown not working in IE8

I'm using the following script to generate a horizontal drop down menu on a site. It works wonderfully in Firefox and Safari, but fails in IE8 (surprise surprise). The intended behavior is that when a main menu item with a submenu is hovered over in the navigation list, the corresponding submenu will appear and any existing submenus in the .submenu div will disappear. In IE8, though, only one of the menu items will display its corresponding submenu (and then only after the link to the left of it, a link without a submenu, has been hovered), and its doing so disables the CSS hover effect on the links. Here's a live example.
I'm not experienced enough in jQuery to know why I might be running into issues, so I'm asking the good folks at StackOverflow for help. Thanks!
(Edit: I'm also running ie7.js on this particular page-- I don't know if that will effect anything or not, but I thought it would be worth mentioning)
$(document).ready(function() {
$('.submenu ul').hide(); //hide all submenus
var msec = document.location.href; //get current url
var mshref = msec.split("/"); //trim URL to include only current section
$('.submenu ul[class~='+mshref[3]+']').show(); //show submenu belonginging to current section
$('.topmenu a').hover(function(){
var msection = $(this).attr("href");
var msechref = msection.split("/");
if($('.submenu ul[class~='+msechref[3]+']').length){ //if there's a submenu belonging to this section
$('.submenu ul').hide();//hide all submenus
$('.submenu ul[class~='+msechref[3]+']').show(); //show the submenu for the section being hovered over
}
else
{
$('.submenu ul').hide();//hide all submenus
$('.submenu ul[class~='+mshref[3]+']').show();//show submenu for current section
}
});
});
And here's the HTML.
<nav><!-- top nav -->
<div class="topmenu">
<ul class="section_list">
<li><a class="active" href="http://test/">Home</a></li>
<li>About</li>
<li>ministries</li>
<li>news</li>
<li>sermons</li>
<li>contact</li>
</ul>
</div>
<div class="submenu">
<ul class="category_list about">
<li>join us</li>
<li>our beliefs</li>
<li>our staff</li>
<li>services</li>
</ul>
<ul class="category_list ministries">
<li>adults</li>
<li>children</li>
<li>preschool</li>
<li>youth</li>
</ul>
</div>
</nav><!-- end of top nav -->
EDIT - Can you try this instead of yours:
$(document).ready(function() {
var root = 'http://www.qualprnt.com/clients/fbcw/', $submenu = $('.submenu ul');
$submenu.hide();
var current = location.href.replace(root, '').split('/')[0];
if(current != '') {
$submenu.filter('.' + current).show();
}
$('.topmenu a').mouseenter(function(){
var section = this.href.replace(root, '').split('/')[0];
$submenu.hide();
if(section != '') {
$submenu.filter('.' + section).show();
}
else {
if(current != '') {
$submenu.filter('.' + current).show();
}
}
return false;
});
});
With this solution, you have to change root variable after you move the site to it's original domain. Please let me know if it works.
I will not delete my old answer, maybe it'll be useful for someone else.
OLD ANSWER:
If you're willing to change your CSS and HTML a little then this solution might be better for you.
HTML:
<nav><!-- top nav -->
<div class="topmenu">
<ul class="section_list">
<li><a class="active" href="http://test/">Home</a></li>
<li>About
<ul class="category_list">
<li>join us</li>
<li>our beliefs</li>
<li>our staff</li>
<li>services</li>
</ul>
</li>
<li>ministries
<ul class="category_list">
<li>adults</li>
<li>children</li>
<li>preschool</li>
<li>youth</li>
</ul>
</li>
<li>news</li>
<li>sermons</li>
<li>contact</li>
</ul>
</div>
</nav><!-- end of top nav -->
Javascript:
$(document).ready(function() {
$('.section_list > li').hover(
function() {
var $this = $(this);
if($this.has('ul')) {
$this.find('ul').show();
}
},
function() {
var $this = $(this);
if($this.has('ul')) {
$this.find('ul').hide();
}
}
);
});
change your script tags:
<script>
to
<script type="text/javascript">

Categories

Resources