Regarding Combining Two Small Javascript Codes - javascript

Basically the question is self explanitory. I can't figure out how to combine small snippets of javascript rather than having two separate files.
The two codes are :
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
});
$(function(){
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Another question, is the first $(function() necessary?
Thanks for you help.

You can do this way:
Create a function and call it under it. Or, you do this:
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Some notes:
Those two functions are different.
You don't need the two function starters, $(function(){}) twice.

You can make it like this:
$(function(){
$('.navbar li, .dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
if($(this).parents(".navbar").length > 0)//this is to figure out if we are working with LI inside .navbar or not.
$(this).addClass('active').siblings().removeClass('active');
else
$(this).removeClass('active')
}
});
});
Functions are almost equal, except that you need to detect if you are working with LI from .navbar or not to select corect removeClass code.
Also, in your code first $(function() is necessary. Otherwise code inside it could be started before document is loaded. But you may put both pieces of code inside one $(function()

Full working sample, this will make the first LI of first UL red, and remove the red from the second ul LI. Your two functions are now combined.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<title></title>
<style type="text/css">
.active {background-color:red}
ul.dropdown-menu>li.active {background-color:red}
</style>
</head>
<body>
</body>
<ul class="navbar">
<li>first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<ul class="dropdown-menu">
<li class="active">first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<script type="text/javascript">
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
</script>
</html>

Related

localStorage onclick add/remove class

The below onclick event is working good. I want the same event should work after we reloading the page also. I tried to implement the localStorage method but not getting the expected output.
Anyone help me resolve this. Thanks in advance!
Script I have tried:
$("ul li").click(function () {
$('ul li').removeClass("one");
$(this).toggleClass("active");
localStorage.setItem('listItem', 'one');
});
$(document).ready(function(){
if(localStorage.getItem('listItem') == 'one') {
$('ul li').addClass("active");
}
});
$('ul li').click(function(){
$("ul li").removeClass("active");
$(this).addClass("active");
});
ul li.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
This is the perfect solution of your problem
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
ul li.active {
color: red;
}
</style>
</head>
<body id="hello">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</body>
</html>
<script type="text/javascript">
$('ul li').click(function(){
$("ul li").removeClass("active");
$('ul li').removeAttr('id');
$(this).addClass("active");
var activeElement = $(this).text();
console.log(activeElement);
localStorage.setItem('active', activeElement);
});
$(document).ready(function(){
$( "ul li" ).each(function( index ) {
if($( this ).text() == localStorage.getItem('active')){
$(this).addClass("active");
}
});
});
</script>
Here is my Fiddle link where you can check your output. Note: clear your localStorage before executing the code.
Try this Tested code. or Click here
Note: keep li id's are unique
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
ul li.active {
color: red;
}
</style>
</head>
<body >
<ul>
<li id="1">One</li>
<li id="2">Two</li>
<li id="3">Three</li>
</ul>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$("ul li").each(function(index) {
if ($(this).attr('id') == localStorage.getItem("Activeli")) {
$(this).addClass("active");
}
});
response = JSON.parse(localStorage.getItem("wishlistID"));
$('a[data-pdtId="' + response + '"]').addClass('active')
});
$('ul li').click(function() {
$("ul li").removeClass("active");
$(this).addClass("active");
var id = $(this).attr("id");
console.log(id);
localStorage.setItem("Activeli", id); //create a localstorage
});
</script>
Hope this help you, thanks

Javascript three-level collapsible menu

I am a complete amateur to coding; I want to have a three-level collapsible menu, which will expand when clicked. I have found some existing code to use, but it is designed for a two-level menu only. I cannot work out how to alter the script so that the third level will open when clicked too. Any ideas would be most appreciated!
Here is the existing script:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!-- <script type="text/javascript" language="javascript" charset="utf-8" src="nav.js"></script> -->
<!--[if lt IE 9]>
<script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>
$(document).ready(function(){
$("#nav > li > a").on("click", function(e){
if($(this).parent().has("ul")) {
e.preventDefault();
}
if(!$(this).hasClass("open")) {
// hide any open menus and remove all other classes
$("#nav li ul").slideUp(350);
$("#nav li a").removeClass("open");
// open our new menu and add the open class
$(this).next("ul").slideDown(350);
$(this).addClass("open");
}
else if($(this).hasClass("open")) {
$(this).removeClass("open");
$(this).next("ul").slideUp(350);
}
});
});
</script>
You can achieve the same outcome with relatively little code compared to what you have there.
Using css to handle the display is arguably easier to manage, with javascript simply toggling a class that you can target in your css. It also means that you can have as many levels as you wish.
It works through the use of the next sibling selector in css +
$('.menu-trigger').click(function(){
$(this).toggleClass('active')
// if you really wish to keep the jquery animation you can do this
// $(this).next('ul').slideToggle()
})
/* you can use the sibling selector '+' to target the list */
.menu-trigger + ul {
display: none;
}
.menu-trigger.active + ul {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a class="menu-trigger">parent</a>
<ul>
<li>
<a class="menu-trigger">child</a>
<ul>
<li>
<a class="menu-trigger">grandchild</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
I wrote this, it is simple but kind of illustrates what you want to achieve.
$('li').hover(function(){
$(this).children('ul:eq(0)').show();
}, function(){
$(this).children('ul:eq(0)').hide();
});
http://codepen.io/clarenswd/pen/GjBaWp

Javascript/jQuery onclick not working

i made a test.html document to test a script. Somehow it is not working and i can't get why nothing is happening. The Script is in -tags and wrapped with -tag and the css also has it´s -tags. Why shouldn't it work? Here is the code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
</script>
<style>
.current {
text-decoration: underline;
}
ul {
list-style-type: none;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<div id="menu">
<ul>
<li><a id="about-link" class="current" href="#">ABOUT</a></li>
<li><a id="events-link" href="#">EVENTS</a></li>
<li><a id="reviews-link" href="#">REVIEWS</a></li>
<li><a id="contact-link" href="#">CONTACT</a></li>
</ul>
</div>
</body>
</html>
Because your code for binding event handler is executed before the elements is present in DOM, the event is not bound on the element.
To solve this problem, you can either
Wrap your code in ready() callback, so that your code will be executed when DOM is finished loading
Move your script to the end of <body>, so all the elements are present in DOM and you can bind the events on it
Code:
$(document).ready(function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
});
EDIT
You can also use load(not recommended) event callback to bind the event, but this will wait for all the resources to load completely.
If you want to use Vanilla Javascript, you can use DOMContentLoaded event on document.
you are executing the code before the DOM content is loaded. Place your code in a ready block.
You are executing the JavaScript before the <body> tag loads, which contains your <li> elements.
To solve this problem, you have three choices :
1.You can insert the JavaScript code you have written inside a $(document).ready() callback. (see http://www.w3schools.com/jquery/event_ready.asp for more information)
Code :
$(document).ready(function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
});
2.You can use the JavaScript's built in window.onload function. (see https://thechamplord.wordpress.com/2014/07/04/using-javascript-window-onload-event-properly/ for more information)
Code:
window.onload = function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
}
3.Place your <script> tag before </body> tag in your page.
Code:
<head>
<style>
.current {
text-decoration: underline;
}
ul {
list-style-type: none;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<div id="menu">
<ul>
<li><a id="about-link" class="current" href="#">ABOUT</a></li>
<li><a id="events-link" href="#">EVENTS</a></li>
<li><a id="reviews-link" href="#">REVIEWS</a></li>
<li><a id="contact-link" href="#">CONTACT</a></li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
</script>
</body>
Note: Using $(document).ready() is a better option than using window.onload. (see window.onload vs $(document).ready() for more information)
Your code is fine. Just wrap it in DOM ready and you are good to go.
$(document).ready(function(){
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
})

Hide jquery menu after click function

I have a simple function to show a dropdown menu.
This is a responsive menu, it only works with defined sizes on my media queries, that's why I want to hide submenu after click.
I want to click on one of the links and then this dropdown menu hides. I am aware of .hide() but I can't get it to work.
Any help?
I want to keep this code simple & clean.
HTML
<nav>
<ul class="navigation">
<img src="img/menu.png" alt="mobile" width="50" height="50"/>
<li class="n1">Principal</li>
<li class="n2">Serviços</li>
<li class="n3">Equipa</li>
<li class="n4">Contactos</li>
</ul>
<span>Euclides Style | 965648044</span>
</nav>
Javascript
$("nav").click(function () {
$(".navigation").toggleClass('open');
});
UPDATE
I used a simple solution:
$(".navigation a").click(function () {
$(".navigation").removeClass('open');
});
Thanks everyone for your help!
hide() is working.
Try:
$("nav li").click(function () {
$(".navigation").hide();
});
DEMO
$("a").on("click", function (e) {
e.preventDefault();
$(".navigation").fadeOut();
});
or you can try .hide() even .fadeOut();
Assuming that open class has display: none or display: block attribute (it depends on the starting state) will work fine.
Alternatively you can use toggle function.
Demo: http://jsfiddle.net/IrvinDominin/uQg2X/
$("nav").click(function () {
$(".navigation").toggleClass('open');
});
and you should add some css
.navigation{ display:'none'}
.navigation.open{display:'block'}
First: it is not allowed to have a img-tag directly inside ul-tag. This is an example of a working code with some modifications:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hiding/showing navigation</title>
<style>
.closed{
display: none;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$("nav").click(function(){
$(".navigation").toggleClass('closed');
});
});
</script>
</head>
<body>
<nav>
<h1>The nav</h1>
<ul class="navigation">
<li class="n1">Principal</li>
<li class="n2">Serviços</li>
<li class="n3">Equipa</li>
<li class="n4">Contactos</li>
</ul>
<span>Euclides Style | 965648044</span>
</nav>
</body>
</html>
The hide(); solution will totally hide the menu and will not show again the next time, the toggle solution will toggle all the other menus on the page, so here below is my solution, this effect will apply to all your dropdown menus on a page.
$(document).on("click",".dropdown-menu li a", function(){
jQuery(this).parent('li').parent('ul').parent('div').removeClass('open');
});

how to target specific css element in javascript?

I've got my code:
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '10px'
}, 400);
});
});
I've got a question about the second line. It won't work. I mean, nothing really animates. The script file is loaded correctly because other functions work. What am I doing wrong here?
try this:
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '+=10px'
}, 400);
});
});
Here I am posting what I got
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '+=10px'
}, 400);
});
});
</script>
</head>
<body>
<div id="topznav">
<ul >
<li>
test1
</li>
<li>
test2
</li>
<li>
test3
</li>
</ul>
</div>
</body>
</html>
This works fine

Categories

Resources