function that calls the next element in a ul - javascript

Trying to understand how Javascript and HTML5 work. I have a nav and when you press Part One I'm trying to show Content 1, when you press Part Two..etc. I have tried a couple things, and I am clearly not understand the .next properly, but I can only get it to show the first element, but when I press Part Two, Content Two doesn't show. I guess I am visualizing it wrong, instead of .first(), .next made sense to me since I feel like that would just get the next element. Anyways, here's some code, thanks in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 6 | jQuery Usability </title>
<link rel="stylesheet" href="stylesheet.css">
<!-- This matches the CSS width to the device width, and prevents forced overview without disabling zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Helpful for older Blackberries -->
<meta name="HandheldFriendly" content="True">
<!-- Helpful for older IE mobile -->
<meta name="MobileOptimized" content="320">
<!-- Apple iOS-specific -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- enforce CSS3 media queries in IE 8 and older -->
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<!-- Note: this won't work when testing locally; you'll need to upload your files to a server to test it in IE -->
<!-- HTML5shiv, for IE 6, 7 and 8 -->
<!--[if lte IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<![endif]-->
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('ul').hide();
$('a.btnDown').click(function() {
$('nav>ul').fadeIn(200);
}); //closes a.btnDown
$('a.contentDown').click(function() {
$('body>aside>ul').first().fadeIn(200);
}); //closes contentDown
}); //closes .ready()
</script>
</head>
<body>
<nav>
<h1><a class="btnDown" href="#"> Main Menu </a></h1>
<ul>
<li><a class="contentDown" href="#"> Part One </a></li>
<li><a class="contentDown" href="#"> Part Two </a></li>
<li><a class="contentDown" href="#"> Part Three </a></li>
<li><a class="contentDown" href="#"> Student Notes 1 </a></li>
<li><a class="contentDown" href="#"> Student Notes 2 </a></li>
<li><a class="contentDown" href="#"> Student Notes 3</a></li>
</ul>
</nav>
<aside>
<ul>
<li> Content 1 </li>
</ul>
<ul>
<li> Content 2 </li>
</ul>
<ul>
<li> Content 3 </li>
</ul>
<ul>
<li> Content 4 </li>
</ul>
<ul>
<li> Content 5 </li>
</ul>
<ul>
<li> Content 6 </li>
</ul>
</aside>
<figure>
<!-- PUT TV IMAGE HERE -->
</figure>
</body>
</html>

With the given markup, the easiest solution is to work with the index of the elements as shown below
$(document).ready(function () {
$('ul').hide();
$('a.btnDown').click(function () {
$('nav>ul').fadeIn(200);
return false;
}); //closes a.btnDown
//all the content elements
var $suls = $('body>aside>ul');
var $as = $('a.contentDown').click(function () {
//hide visible content item
$suls.filter(':visible').hide();
//display the content item in the same position as the clicked contentDown
$suls.eq($as.index(this)).fadeIn(200);
}); //closes contentDown
}); //closes .ready()
Demo: Fiddle

You can use:
$('ul').hide();
$('a.btnDown').click(function () {
$('nav>ul').fadeIn(200);
});
$('a.contentDown').click(function () {
var idx = $(this).index('.contentDown');
$('body>aside>ul:eq(' + idx + ')').fadeIn(200).siblings('ul').hide();
});
Fiddle Demo

Related

jQuery load executes but callback is not executed

I am kinda new to website development, so I am asking for some help on the matter. I have the following snippet of html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--CSS Styles -->
<link rel="stylesheet" href="../assets/css/styles.css"/>
</head>
<body>
<!--Navigation bar-->
<div id="nav-placeholder"></div>
<!--end of Navigation bar-->
</body>
<script src="../assets/js/navigation_bar.js" type="text/javascript", locator="about"></script>
</html>
It calls the navigation_bar.js script provided here
locator = document.currentScript.getAttribute('locator');
function changeActiveElement(element_id){
console.log("Called");
nav_element = document.getElementById("navigation");
for (i = 0; i < nav_element.length; i++) {
console.log(nav_element[i].id)
if(nav_element[i].id == element_id) document.getElementById(element_id).className = "active-nav-link";
else document.getElementById(element_id).className = "nav-link";
}
}
$(function()
{$("#nav-placeholder").load("/assets/html/nav.html", function(){
changeActiveElement(locator);
});}
);
whereas the nav.html file is here:
<nav>
<h1>Some name</h1>
<ul id="navigation" class="navigation">
<li><a id="about" href="/pages/about.html" class="nav-link">About</a></li>
<li><a id="compt" href="#compt" class="nav-link">Competences</a></li>
<li><a id="projects" href="#projects" class="nav-link">Projects</a></li>
<li><a id="contact" href="#contact" class="nav-link">Contact</a></li>
</ul>
<button class="burger-menu" id="burger-menu">
<ion-icon class="bars" name="menu-outline"></ion-icon>
</button>
</nav>
The scope of the snippet is to change the class of the a tags listed in the navigation element. The navigation bar is correctly loaded via $("#nav-placeholder").load("/assets/html/nav.html"), yet changeActiveElement function is never executed via the callback.
Can someone explain me this behaviour?
I tested your code and everything is working except that nav_element is not a list and therefore nav_element.length throws an error. You could use document.querySelectorAll("#navigation"); instead, which returns a node list of all selected elements. Although, I would not recommend doing a for loop on elements by id. Use classes to select the elements. Id is only for one element.

Creating a life system like video games on a quiz

I'm creating some web pages for an escape game. They mostly serve to gather responses and check if they are correct. In this case, it is a letter to put in the right order. The sorting script was taken from Codepen, then I've modified some JavaScript to monitor the if/else condition. If it is wrong, you loose a life. The code does that is the answer is wrong, it deletes one of the four images representing the life.
I've searched everywhere how to build a life system, so I tried some theories I've made in my mind, but I'don't have a good understanding of JavaScript yet to achieve what I want to do.
$(function() {
$("#sortable").sortable();
$("#sortable").disableSelection();
});
function checkOrd() {
var life = document.getElementById('life');
var items = $('#sortable li').map(function() {
return $.trim($(this).attr('id'));
}).get();
var itsort = $('#sortable li').map(function() {
return $.trim($(this).attr('id'));
}).get();
<!-- console.log(items); -->
<!-- console.log(itsort); -->
itsort.sort();
if (JSON.stringify(items) == JSON.stringify(itsort))
alert("Right order!");
else
life.parentNode.removeChild(life);
};
<DOCTYPE! html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Style.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
</script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<img id="life" src="life.png"><img id="life" src="life.png"><img id="life" src="life.png"><img class="life" src="life.png"> </div>
<div class="Lettre">
<ul id="sortable">
<li class="intro">INTRO TEXT</li>
</br>
<li class="partie" id="3">TEXT </li>
<li class="partie" id="2">TEXT </li>
<li class="partie" id="4">TEXT </li>
<li class="partie" id="1">TEXT </li>
<li class="outro" id="5">ENDING TEXT</li>
</ul>
</div>
<div class="confirmbutton" style="display: flex !important;justify-content: center !important">
<button id="confirm" onclick="checkOrd();">Confirmer</button>
</div>
</html>
Is there a better way to handle this? If I work like that, I still haven't found a way to report the remaining life in the next pages.
This is basically how you can do it:
function removeLife(){
$(".life").last().remove();
}
function countLives(){
return $(".life").length;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<style>
#lives{
padding:0;
}
.life{
display: inline;
}
</style>
<body>
<ul id="lives">
<li class="life">Life 1</li>
<li class="life">Life 2</li>
<li class="life">Life 3</li>
<li class="life">Life 4</li>
</ul>
<button onclick="removeLife()">Remove a life</button>
<button onclick="alert(countLives())">Get remaining lives</button>
</body>
</html>
You can then check how many lives are left with something like
function countLives(){
return $(".life").length;
}

Materializecss sidenav not working

I am trying to get the sidenav to work for the Materializecss framework.
MATERIALIZECSS http://next.materializecss.com/getting-started.html
SIDENAV DEMO http://next.materializecss.com/sidenav.html
MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
</body>
3 Days trying to figure this out :/ so any help is welcomed.
The problem is that you should initialize the side-nav in Javascript code like this
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// with jquery
$(document).ready(function(){
$('.sidenav').sidenav();
});
now your code will work perfect
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// Initialize collapsible (uncomment the lines below if you use the dropdown variation)
// var collapsibleElem = document.querySelector('.collapsible');
// var collapsibleInstance = new M.Collapsible(collapsibleElem, options);
// Or with jQuery
$(document).ready(function(){
$('.sidenav').sidenav();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><div class="user-view">
<div class="background">
<img src="images/office.jpg">
</div>
<img class="circle" src="images/yuna.jpg">
<span class="white-text name">John Doe</span>
<span class="white-text email">jdandturk#gmail.com</span>
</div></li>
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
</body>
On the materialize website, this code is given to initialize Sidenav bar
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems, options);
});
but You modify This code and remove option in var instance and now code look like and you should paste this code in your script tag or your javascript file
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
Now I explain what is the problem in upper code that given on the materialize website
in code, variable instances give 2 arguments 1st argument is elems and 2nd argument is the option that is not defined in your code so you remove the option argument in this code to solve this problem
Initialization is the most important thing when using materialize.js, for example i want to initialize a carousel.
// Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.carousel');
var instances = M.Carousel.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.carousel').carousel();
});

Bootstrap 3 nav-tabs won't change on click

So I just started a new site in bootstrap and I'm working on a nav-tabs design. I've followed the directions to the tee and have almost copied and pasted at this point just to get it to function but alas I have several problems:
(1) The nav-tabs do not change on click i.e. the url changes to my element id but the actual tab does not become "active" (Home remains depressed while the others stay unpressed)
(2) The tab-content div only displays the content marked by class="active".
I have included the necessary jquery and bootstrap js scripts and I believe they are in the correct order but no matter what I do these tabs never switch their active state to the one that is clicked.
Here is my html:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-1.11.2.min" type="text/javascript"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<title>New Homepage w/ Bootstrap</title>
</head>
<body>
<div class="nav">
<div class="container">
<div class="tabbable">
<ul class="nav nav-tabs" data-tabs="tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#home">Home</a></li>
<li><a data-toggle="tab" href="#about">About</a></li>
<li><a data-toggle="tab" href="#subscribe">Subscribe</a></li>
<li><a data-toggle="tab" href="#search">Search</a></li>
<li><a data-toggle="tab" href="#logout">Logout</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">
<h1>Hospital Data Solutions</h1>
<p>Financial Analysis Database</p>
</div>
<div class="tab-pane" id="about">
<h1>About Us</h1>
<p>Cost Reports and Financial Analysis Nationwide Database</p>
</div>
<div class="tab-pane" id="subscribe">
<h1>Annual Subscription</h1>
<p>Purchase an annual subscription to access all cost reports.</p>
<h2>Individual Cost Reports</h2>
<p>Purchase individual cost reports directly from us in .pdf, .xs, .csv formats.</p>
</div>
<div class="tab-pane" id="search">
<h1>Search our database</h1>
<p>Search content goes here.</p>
</div>
<div class="tab-pane" id="logout">
<h1>logout</h1>
<p>Logout fx goes here.</p>
</div>
</div>
</div>
</div>
</div>
<script src="js/bootstrap.js"></script>
</body>
</html>
I have attempted the various solutions I could find including the addition of
<script>
$(document).ready(function () {
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.relatedTarget // previous tab
});
});
</script>
Underneath the bootstrap.min.js script but like I said just about anything I've done has produced NO change whatsoever. Everything else looks fine on the page but a little guidance here would truly get me started on the right foot. I haven't been working with bootstrap for more than a few hours so forgive my ignorance. The docs say that bootstrap does not even require javascript to toggle the tabs when data-toggle is used so I'm quite confused on what the right answer is.
:EDIT: The first answer was correct. Placing the tags right before the closing body tag did not improve functionality but replacing my scripts with
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.relatedTarget // previous tab
});
});
</script>
Did indeed work. I my initial jquery and bootstrap files were in the correct place but it seems they are not completely functional/broken in some way or something. Thanks again!
By the way: Am I able to link to these repositories constantly or will I have to update my pages when new updates of bootstrap/jquery come out? What I'm asking is will these repositories will be deleted?
The only thing I can think of (but what usually causes this issue) is your <link> and <script> tags are in the wrong spot. Copying your code to an editor of mine and adding jquery.min.js and bootstrap.min.js right before the closing </body> tag caused it to work just fine for me. Here is the HTML file:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href=".../bootstrap.min.css" rel="stylesheet" type="text/css"/>
<title>New Homepage w/ Bootstrap</title>
</head>
<body>
<div class="nav">
<div class="container">
<div class="tabbable">
<ul class="nav nav-tabs" data-tabs="tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#home">Home</a></li>
<li><a data-toggle="tab" href="#about">About</a></li>
<li><a data-toggle="tab" href="#subscribe">Subscribe</a></li>
<li><a data-toggle="tab" href="#search">Search</a></li>
<li><a data-toggle="tab" href="#logout">Logout</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">
<h1>Hospital Data Solutions</h1>
<p>Financial Analysis Database</p>
</div>
<div class="tab-pane" id="about">
<h1>About Us</h1>
<p>Cost Reports and Financial Analysis Nationwide Database</p>
</div>
<div class="tab-pane" id="subscribe">
<h1>Annual Subscription</h1>
<p>Purchase an annual subscription to access all cost reports.</p>
<h2>Individual Cost Reports</h2>
<p>Purchase individual cost reports directly from us in .pdf, .xs, .csv formats.</p>
</div>
<div class="tab-pane" id="search">
<h1>Search our database</h1>
<p>Search content goes here.</p>
</div>
<div class="tab-pane" id="logout">
<h1>logout</h1>
<p>Logout fx goes here.</p>
</div>
</div>
</div>
</div>
</div>
<script src=".../jquery.min.js" type="text/javascript"></script>
<script src=".../bootstrap.min.js" type="text/javascript"></script>
</body>
</html>
Note: Replace .../ with the correct URL to bootstrap.min.css, jquery.min.js and bootstrap.min.js. Hope that helps!
The tabs are working fine as can be seen here: https://jsfiddle.net/AndrewL32/nh6ma48r/
<script type="text/javascript">
$(document).ready(function () {
$('#myTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.relatedTarget // previous tab
});
});
</script>
You need to keep bootstrap.js as well as the above script that calls the function above on your <head></head> section but below your jQuery.
Also, please replace your:
<script src="bootstrap.js"></script> with this <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
and your
<script src="jQuery"></script> with this <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
(issue could be because your js files are edited, moved or missing)

How to expand a collapsible item from link within another collapsible item [js]?

I'm making a list of collapsible items that can make calls to itself to scroll to and expand other items on the fly. Shooting for this...
Before selecting the hyperlink.
After selecting.
How can I get the First collapsed item to expand when the link to it in the Third item's paragraph is selected?
What I got: If the example above had more collapsed items, then the code below would scroll the webpage to the desired collapsible item (half the solution).
<!DOCTYPE html>
<html>
<head>
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<body>
<div>
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i><a name="987"/>First</a></div>
<div class="collapsible-body"><p>Hello StackOverflow! SO's da' bomb diggidy!</p></div>
</li>
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i>Second</div>
<div class="collapsible-body"><p>Why is the person who invests your money called a broker?</p></div>
</li>
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i>Third</div>
<div class="collapsible-body"><p>I'd like to open the First collapsible element in this list.</p></div>
</li>
</ul>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
I would just trigger click event on first .collapsible-header item, with slightly changed html code for the anchor:
$('[data-click]').on('click', function (e) {
$( $(this).data('click') ).trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/css/materialize.min.css" rel="stylesheet"/>
<div>
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i>First</div>
<div class="collapsible-body">
<p>Hello StackOverflow! SO's da' bomb diggidy!</p>
</div>
</li>
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i>Second</div>
<div class="collapsible-body">
<p>Why is the person who invests your money called a broker?</p>
</div>
</li>
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i>Third</div>
<div class="collapsible-body">
<p>I'd like to open the First collapsible element in this list.</p>
</div>
</li>
</ul>
</div>
Same code is also on Fiddle.
If you wish to target n-th element, than you can use jQuery :eq() selector (zero based). For example, to target 3rd item you would use '.collapsible-header:eq(2)' selector.
If you care about the SEO (and you should), than your links should have correct href. In this case add unique IDs to .collapsible_header elements and use slightly different script to exploit it:
$('[data-click]').on('click', function (e) {
$( $(this).attr('href') ).trigger('click');
});
where the target item is:
<div id="about_stackoverflow" class="collapsible-header">
and the valid local link is:
open the First collapsible element
You can see it working on this Fiddle. (The last anchor may be anywhere on the same page)

Categories

Resources