Materializecss sidenav not working - javascript

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();
});

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.

JS works on CodePen but not locally [duplicate]

This question already has answers here:
Why is simple JavaScript code not running?
(3 answers)
Closed 1 year ago.
I'm trying to get a JS slider to work. I'm using Brackets as my code environment.
I have tried creating a local .js file and putting
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
<script type="text/javascript" src="my.js"></script>
line in <head>
I have also tried just putting only <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> in <head> and then putting all of the script code within a <script> tag in <head>.
CodePen for that:
https://codepen.io/hiarooo/pen/zYNboJq
As you can see, the slider doesn't function properly.
However, I have noticed that if I simply put the code in the JS box of CodePen (I have commented it, but you can try uncommenting it to see what I mean) then the Slider functions perfectly.
What is wrong with the way I am doing things? I do not understand.
Thank you for any advice.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypter | Upload01</title>`enter code here`
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght#700&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!--<script type="text/javascript" src="my.js"></script>-->
</head>
<body>
<section class="section-slider">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Neucha' rel='stylesheet' type='text/css'>
<div id="wrapper">
<div id="slider-wrap">
<ul id="slider">
<li data-color="#1abc9c">
<div>
<h3>What is cat</h3>
<span>it is a cat</span>
</div>
<i></i>
</li>
<li data-color="#3498db">
<div>
<h3>Slide #2</h3>
<span>Sub-title #2</span>
</div>
<i class="fa fa-gears"></i>
</li>
<li data-color="#9b59b6">
<div>
<h3>Slide #3</h3>
<span>Sub-title #3</span>
</div>
<i class="fa fa-sliders"></i>
</li>
<li data-color="#34495e">
<div>
<h3>Slide #4</h3>
<span>Sub-title #4</span>
</div>
<i class="fa fa-code"></i>
</li>
<li data-color="#e74c3c">
<div>
<h3>Slide #5</h3>
<span>Sub-title #5</span>
</div>
<i class="fa fa-microphone-slash"></i>
</li>
</ul>
<!--controls-->
<div class="btns" id="next"><i class="fa fa-arrow-right"></i></div>
<div class="btns" id="previous"><i class="fa fa-arrow-left"></i></div>
<div id="counter"></div>
<div id="pagination-wrap">
<ul>
</ul>
</div>
<!--controls-->
</div>
</div>
</section>
<script>
//current position
var pos = 0;
//number of slides
var totalSlides = $('#slider-wrap ul li').length;
//get the slide width
var sliderWidth = $('#slider-wrap').width();
$(document).ready(function(){
/*****************
BUILD THE SLIDER
*****************/
//set width to be 'x' times the number of slides
$('#slider-wrap ul#slider').width(sliderWidth*totalSlides);
//next slide
$('#next').click(function(){
slideRight();
});
//previous slide
$('#previous').click(function(){
slideLeft();
});
/*************************
//*> OPTIONAL SETTINGS
************************/
//automatic slider
var autoSlider = setInterval(slideRight, 3000);
//for each slide
$.each($('#slider-wrap ul li'), function() {
//set its color
var c = $(this).attr("data-color");
$(this).css("background",c);
//create a pagination
var li = document.createElement('li');
$('#pagination-wrap ul').append(li);
});
//counter
countSlides();
//pagination
pagination();
//hide/show controls/btns when hover
//pause automatic slide when hover
$('#slider-wrap').hover(
function(){ $(this).addClass('active'); clearInterval(autoSlider); },
function(){ $(this).removeClass('active'); autoSlider = setInterval(slideRight, 3000); }
);
});//DOCUMENT READY
/***********
SLIDE LEFT
************/
function slideLeft(){
pos--;
if(pos==-1){ pos = totalSlides-1; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************
SLIDE RIGHT
*************/
function slideRight(){
pos++;
if(pos==totalSlides){ pos = 0; }
$('#slider-wrap ul#slider').css('left', -(sliderWidth*pos));
//*> optional
countSlides();
pagination();
}
/************************
//*> OPTIONAL SETTINGS
************************/
function countSlides(){
$('#counter').html(pos+1 + ' / ' + totalSlides);
}
function pagination(){
$('#pagination-wrap ul li').removeClass('active');
$('#pagination-wrap ul li:eq('+pos+')').addClass('active');
}
</script>
</body>
Try putting this way it works fine,because If you have code in your JavaScript that alters HTML as soon as the JavaScript file loads, there won't actually be any HTML elements available for it to affect DOM yet, so it will seem as though the JavaScript code isn't working, and you may get errors.Thanks :)

adding .className to object is not working

I am attempting to set a className to my nav element and it isn't working as intended. When I manually add the class to my HTML it puts a border around the unordered list items and the buttons. When I use js to add it, it shows that the nav tag has the attribute in the inspector but it does not add the border so I do not believe it is working. What am I doing wrong? I have linked to the bootstrap cdn and jquery cdn in the file.
HTML
<!doctype html>
<html lang="en-us">
<head>
<title>Exercise 5.9</title>
<meta charset="UTF-8">
<meta equiv="X-UA-Compatible" content="IE=Edge">
</head>
<body id="content">
<!-- Latest compiled and minified CSS -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<nav>
<div>
<ul>
<li>Home</li>
<li>Our Policies</li>
<li>How you can help</li>
<li>What we have accomplished</li>
<button type="button">Donate $10.00</button>
<button type="button">Donate $50.00</button>
<button type="button">Donate $100.00</button>
</ul>
</div>
</nav>
<p>If you would to offer financial support, please choose the buttons above</p>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="exercise-5.9.js"></script>
</body>
</html>
JS
var nav = document.getElementsByTagName("nav");
nav.className = "navbar navbar-default";
console.log(nav);
Instead of using .className = try just setting the attribute of class to whatever you want. The main reason why it's not working, however, is because .getElementsByTagName() returns an array (nodeList) so you need to make sure when you set the class, it's properly indexed.
Using .setAttribute("atr", "value")
var button = document.getElementById("btnGo");
button.onclick = function () {
var nav = document.getElementsByTagName("nav");
for (var i = 0; i < nav.length; i++) {
nav[i].setAttribute("class", "myClassName");
}
};
Using .className
var button = document.getElementById("btnGo");
button.onclick = function () {
var nav = document.getElementsByTagName("nav");
for (var i = 0; i < nav.length; i++) {
nav[i].className = "myClass";
}
};
getElementsByTagName() return an array, you should write document.getElementsByTagName('nav')[0];

Simple Javascript error that is driving me insane

This is driving me nuts. I have put the html and javaScript code below. Whenever I refresh my page I get Uncaught TypeError: screen.addEventListener is not a function. I insert any other variable or ID for screen and it works fine.
HTML Code
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
<link rel="stylesheet" href="css/reset/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="calculator">
<div id="screen">
</div>
<div id="layout">
<ul id="first-row" class="btn-row">
<li><button>C</button></li>
<li><button>=</button></li>
</ul>
<ul id="sec-row" class="btn-row">
<li><button>7</button></li>
<li><button>8</button></li>
<li><button>9</button></li>
<li><button>+</button></li>
</ul>
<ul id="third-row" class="btn-row">
<li><button>4</button></li>
<li><button>5</button></li>
<li><button>6</button></li>
<li><button>-</button></li>
</ul>
<ul id="fourth-row" class="btn-row">
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>*</button></li>
</ul>
<ul id="fifth-row" class="btn-row">
<li><button>0</button></li>
<li><button>/</button></li>
</ul>
</div>
</div>
<script src="js/app.js">
</script>
</body>
</html>
JavaScript Code
var screen = document.getElementById('screen');
var btn = document.getElementsByTagName('button');
var clear = btn[0];
var equals = btn[1];
var seven = btn[2];
clear.addEventListener('click', here);
screen.addEventListener('click', function(){
alert('wth');
});
You have a naming issue. It is clashing with the window.screen object
console.log(window.screen);
MDN window.screen
Rename the variable to something else and it works fine.
var screenX = document.getElementById("screen");
screenX.addEventListener("click", function() { alert("x"); });
<div id="screen">Click</div>
or take it out of global scope
(function () {
var screen = document.getElementById("screen");
screen.addEventListener("click", function() { alert("x"); });
}());
<div id="screen">Click</div>

function that calls the next element in a ul

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

Categories

Resources