How to create a new div each time a button is clicked? - javascript

This is my code:
function newMentee() {
document.getElementById('new-mentee-form').style.display="block";
document.getElementById('mentees').style.display="none";
}
function addMentee() {
document.getElementById('new-mentee-form').style.display="none";
document.getElementById('mentees').innerHTML=document.getElementById('name').value+'<br><br>'+document.getElementById('rating').value+'<br><br>'+document.getElementById('comments').value;
document.getElementById('mentees').setAttribute("style","display:block;background-color:black;width:10em;height:10em;margin-top:5em;margin-left:2em;padding:2em;border-radius:2em;word-wrap:break-word;");
}
* {
margin: 0;
padding: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
background-color: #3b4149;
}
header {
background-color: #181b1e;
width: 100%;
height:15em;
}
header h1 {
color:white;
text-align: center;
line-height: 5em;
font-size: 3em;
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
ul li {
display: block;
float:left;
width: 25%;
text-align: center;
line-height: 2.5em;
color:white;
background-color: #1376d8;
}
ul li ul li {
display: none;
}
ul li:hover {
background-color: #18e288;
opacity: 0.7;
}
ul li:hover ul li {
display: block;
width:100%;
}
#new-mentee-form {
padding-top: 3em;
color:white;
background-color: black;
width:20em;
height:30em;
margin-top: 3em;
border-radius: 2em;
display: none;
}
input,textarea {
padding: 0.5em;
color:white;
}
#submit {
border-radius: 2em;
}
#submit:hover {
background-color: #18e288;
}
textarea {
resize:none;
}
#mentees {
color:white;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="delta.css">
<script type="text/javascript" src="delta.js">
</script>
</head>
<body>
<header>
<h1>Mentee List</h1>
</header>
<nav>
<ul>
<li>List of Mentees</li>
<li onclick="newMentee();">Add a mentee</li>
<li>Remove a mentee</li>
<li>Make an edit
<ul>
<li>Add Details</li>
<li>Remove Details</li>
</ul>
</li>
</ul>
</nav>
<div id="mentees">
</div>
<center>
<div>
<div id="new-mentee-form">
Name:<br><br><input type="text" name="name" id="name"><br><br>
Rating:<br><br><input type="text" id="rating" value=""><br><br>
Comments:<br><br><textarea name="name" rows="8" cols="28" id="comments" maxlength="30"></textarea><br><br>
<input type="submit" name="submit" value="Submit" id="submit" onclick="addMentee();">
</div>
</div>
</center>
</body>
</html>
My goal is to create a new div(this will be displayed like a card) with all the details entered by the user each time "Add Mentee" in the navigation bar is clicked. I do not want to store the data in an external file. Is there any way to retrieve the previous data from innerHTML and add a new div to the existing content of innerHTML? The problem I'm facing is that each time "Add Mentee" is clicked the previous data is wiped out. I want to do this in VanillaJS.

while assigning new value to innerHTML, you can append it with old value as
document.getElementById('mentees').innerHTML+='<br >' + document.getElementById('name').value+'<br><br>'+document.getElementById('rating').value+'<br><br>'+document.getElementById('comments').value;

div.innerHTML = div.innerHTML + newDiv
Or
div.appendChild(newDiv)
See ref:
https://www.w3schools.com/jsref/met_node_appendchild.asp

Related

onClick JS not go to top of the page

I have a page with an initial description, followed by 2 buttons, where the user can choose typeA or typeB. They work by "target": when the user clicks typeA comes the content relative to typeA, bellow the buttons; same to typeB.
typeA is the most common selection, then, when the page loads, a javascript emulates the click to typeA and opens respective content. To avoid hidden the initial description, there is another javascript to put the page at the top. Worked on Chrome and Edge, not on Firefox.
I would like to repeat the same process when the user clicks: opens the respective content, but positioning the page at the top, or, at least, showing the buttons. I thought event onClick calling the same js backToTop would worked - but not.
I put an alert on js and enters there but not execute: always keeps the content of the button selected in its better visibility.
I tried:
window.location.href = '#top';
window.scrollBy(0, -500);
document.html.scrollTop = document.documentElement.scrollTop = 0;
without success.
What am I doing wrong?
<head>
<meta charset="UTF-8">
<title>TOP PAGE TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body,html {margin-left:auto; margin-right:auto;width:70%; font-family:verdana; font-size:1.2em;}
.menuFAQ {background:#aaa; font-size:2em; width:100%;}
.menuFAQ ul {list-style-type:none; position:relative; margin-left:-40px; /* to avoid user agent chrome */}
.menuFAQ li {display:inline-block; margin-top:10px; margin-bottom:10px; width:49%; background:#fff; text-align:center; box-shadow:2px 3px 4px 0px rgba(170,170,170,1); font-weight:400; line-height:80px;}
.menuFAQ li a {display:block; color:#020062; background:#fff; font-weight:400; text-decoration:none;}
.menuFAQ li .active,.menuFAQ li:hover a {color:#fff; font-weight:400; background-image:linear-gradient(#165686, #0f3a5a); }
:target {color:#fff;font-size:1em;}
div.items>div:not(:target) {display:none}
div.items>div:target {display:block; margin-left:auto; margin-right:auto; color:#000; border:1px solid #aaa;}
</style>
</head>
<body>
<div id="top">Top Page</div>
<br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5
<div class="menuFAQ">
<ul>
<li><a id="preferedFAQ" onclick="backToTop()" class="target" href="#typeA">TypeA</a></li>
<li><a onclick="backToTop()" class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p><p>text2B</p><p>text3B</p>
<br>[...]
</nav>
</div>
</div>
<script>
const allTargetLinks = document.querySelectorAll('.target')
allTargetLinks.forEach(targetLink => {
targetLink.addEventListener('click', () => {
allTargetLinks.forEach(targetLink => {
targetLink.classList.remove('active')
})
targetLink.classList.add('active')
})
})
window.onload = function() {assignPreferedFAQ()};
function assignPreferedFAQ() {
document.getElementById("preferedFAQ").click();
backToTop();
};
function backToTop() {
//document.html.scrollTop = document.documentElement.scrollTop = 0;
//document.body.scrollTop = document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
};
</script>
You had a real mess there regarding how you process click events and href attribute, i.e:
You had onclick attribute on your links, and you were adding yet another listener to them in JS
You didn't event.preventDefault() in your function, and default browser behavior when you click on a link is to get you to its href path
I've cleaned up a bit and changed some things. Since we need to prevent default behavior :target selector will no longer work, so instead I did what you've already been doing with links, and added an active class to your content. clickHandler() will now remove and add class active as necessary. At the end just scroll to the top. Here's the snippet:
document.querySelectorAll('.target').forEach(targetLink => targetLink.addEventListener('click', clickHandler, false));
function clickHandler(ev) {
ev.preventDefault(); // prevent browser from automatically scrolling to href pos
if (!ev.currentTarget.classList.contains('active')) {
// disable active elements
document.querySelector('.target.active').classList.remove('active');
document.querySelector('.items div.active').classList.remove('active');
// add class to the clicked on button and its corresponding content tab
ev.currentTarget.classList.add('active');
// to prevent pointless string slicing below, you'd have to store ids somewhere else i.e in the data-id attribute
const id = ev.currentTarget.href.slice(ev.currentTarget.href.lastIndexOf('#') + 1);
document.getElementById(id).classList.add('active');
}
window.scrollTo(0,0);
}
* {
font-family: verdana;
font-size: 1em;
}
.menuFAQ {
background: #aaa;
font-size: 2em;
width: 100%;
}
.menuFAQ ul {
list-style-type: none;
text-align: center;
padding: 0;
/* to avoid user agent chrome */
}
.menuFAQ li {
display: inline-block;
width: 48%;
margin-top: 10px;
margin-bottom: 10px;
background: #fff;
text-align: center;
box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
font-weight: 400;
line-height: 80px;
}
.menuFAQ li a {
display: block;
color: #020062;
background: #fff;
font-weight: 400;
text-decoration: none;
}
.menuFAQ li .active,
.menuFAQ li:hover a {
color: #fff;
font-weight: 400;
background-image: linear-gradient(#165686, #0f3a5a);
}
div.items>div {
display: none;
}
div.items>div.active {
display: block;
margin-left: auto;
margin-right: auto;
color: #000;
border: 1px solid #aaa;
}
<div id="top">Top Page</div>
<br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5
<div class="menuFAQ">
<ul>
<li><a class="target active" href="#typeA">TypeA</a></li>
<li><a class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div class="active" id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p>
<p>text2B</p>
<p>text3B</p>
<br>[...]
</nav>
</div>
</div>
Note that instead of artificially clicking at the page load, now your content just loads with class active.
Hope this help you.
< script >
window.onload = function() {
document.getElementById("preferedFAQ").click();
backToTop();
};
function backToTop() {
document.documentElement.scrollTop = document.body.scrollTop = 0;
//alert("enter backToTop");
var elmnt = document.getElementById("top");
var x = elmnt.scrollLeft;
var y = elmnt.scrollTop;
}; <
/script>
body,
html {
margin-left: auto;
margin-right: auto;
width: 70%;
font-family: verdana;
font-size: 1.2em;
}
.menuFAQ {
background: #aaa;
font-size: 2em;
width: 100%;
}
.menuFAQ ul {
list-style-type: none;
position: relative;
margin-left: -40px;
/* to avoid user agent chrome */
}
.menuFAQ li {
display: inline-block;
margin-top: 10px;
margin-bottom: 10px;
width: 49%;
background: #fff;
text-align: center;
box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
font-weight: 400;
line-height: 80px;
}
.menuFAQ li a {
display: block;
color: #020062;
background: #fff;
font-weight: 400;
text-decoration: none;
}
.menuFAQ li .active,
.menuFAQ li:hover a {
color: #fff;
font-weight: 400;
background-image: linear-gradient(#165686, #0f3a5a);
}
:target {
color: #fff;
font-size: 1em;
}
div.items>div:not(:target) {
display: none
}
div.items>div:target {
display: block;
margin-left: auto;
margin-right: auto;
color: #000;
border: 1px solid #aaa;
}
<div id="top">Top Page</div> <br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5<br>textExp6<br>textExp7<br>textExp8<br>textExp9<br>textExpA<br>textExpB<br>textExpC<br>textExpD
<br>textExpE
<div class="menuFAQ">
<ul>
<li><a id="preferedFAQ" onclick="backToTop()" class="target" href="#typeA">TypeA</a></li>
<li><a onclick="backToTop()" class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p>
<p>text2B</p>
<p>text3B</p>
<br>[...]
</nav>
</div>
</di

Search results won't filter properly [jquery]

Hi small disclaimer: I have learning disability, sorry in advance.
I have to do a jquery assignment where we make products and then the option to filter them through checkboxes. Now I followed everything we learned in the lesson and tried to apply it but it refuses to filter...
$('.fruit').hide();
$('#fruitCheck').click(function() {
if ($(this).is(':checked')) {
$('.fruit').show();
} else {
$('.fruit').hide()
}
};
ul
{
list-style-type: none;
}
div ul li
{
margin: 5px;
float: left;
}
img
{
}
.fruit p
{
float: left;
position: absolute;
margin-top: -15px;
margin-left: 20px;
background-color: green;
font-size:10px;
padding-left:20px;
padding-right:20px;
opacity: 0.8;
}
.frisdrank p
{
float: left;
position: absolute;
margin-top: -15px;
margin-left: 20px;
background-color: red;
font-size:10px;
padding-left:20px;
padding-right:20px;
opacity: 0.8;
}
.dier p
{
float: left;
position: absolute;
margin-top: -15px;
margin-left: 20px;
background-color: yellow;
font-size:10px;
padding-left:20px;
padding-right:20px;
opacity: 0.8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title> </title>
</head>
<body>
<label for="fruitCheck">
<input type="checkbox" id="fruitcheck" />
Fruit
</label>
<div class="row">
<ul>
<li class="frisdrank"><img src="https://i.imgur.com/FW5hGnb.png" /><p>Cola</p></li>
<li class="frisdrank"><img src="https://i.imgur.com/N3U2j5t.png" /><p>Fanta</p></li>
<li class="fruit"><img src="https://i.imgur.com/7yazXfi.png"/><p> Appel</p></li>
<li class="fruit"><img src="https://i.imgur.com/R4bx4kT.png" /><p>Peer</p></li>
<li class="dier"><img src="https://i.imgur.com/JshZluf.png" /><p>Hond</p></li>
<li class="dier"><img src="https://i.imgur.com/00auPwp.png" /><p>Kat</p></li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="hello_world.js"></script>
</body>
</html>
Right now it looks like this: https://i.imgur.com/p1PctA3.png
fiddle: https://jsfiddle.net/97nd3t81/
PS. I know there's only 1 checkbox now, I was planning on just copy pasting them after I had the first one working.
Updated your JSfiddle, check it here.
$('.fruit').hide();
$('#fruitcheck').click(function() {
if ($(this).is(':checked')) {
$('.fruit').show();
} else {
$('.fruit').hide()
}
});
Only missing thing was a parenthesis at the end of the .click function. You can find the .click function documentation here.
Change
<label for="fruitCheck">
<input type="checkbox" id="fruitcheck" />
Fruit
</label>
to
<input id='fruitcheck' type='checkbox' /><lable for='fruitcheck'>Fruit</label>
Then you can do:
var fruits = $('.fruit'), fruitcheck = $('#fruitcheck');
fruitcheck.prop('checked', false); fruit.hide();
fruitcheck.click(function(){​
if(fruitcheck.is(':checked')) {​
fruits.show();
}
else{​
fruits.hide();
}
});

JQuery to do list project

This is a To Do List Project using html css and jquery
Every time i add something the list moves down , i don't know if it is because of css or jquery, you can see the code down below to check it, please help!!
It's always trying to be at the same level as the new list that is being added via JQuery.
Also when i did some validation so that when the user enters nothing it doesn't add it to the list, this worked for monday but all other days it didn't work even though i used the tag in script.js
http://mohammadhalawi.6te.net/To%20Do%20List/Index.html
I uploaded it online if you want to check it out
HTML
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>JQuery MealPlaner</title>
<link rel="stylesheet" type="text/css" href="Normalize.css">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="jquery-ui-1.11.4/jquery-ui.min.css" rel="stylesheet">
</head>
<body>
<div class="container" id="todoListWrapper">
<h1>The JQuery To Do List</h1>
<div id="todoList" class="clearfix">
<ul>
<li class="listTitle">Monday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul >
<li class="listTitle">Tuesday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul >
<li class="listTitle">Wednesday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul >
<li class="listTitle">Thursday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul>
<li class="listTitle">Friday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul>
<li class="listTitle">Saturday</li>
<li class="addItem">
<input type="text" class="inputItem" placeholder="add new item...">
</li>
</ul>
<ul >
<li class="listTitle" >Sunday</li>
<li class="addItem">
<input type="text" placeholder="add new item...">
</li>
</ul>
</div>
</div>
<div id="trash">
Drop Here!
</div>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script>
window.jQuery || document.write('<script src="JQuery.js"><\/script>');
</script>
<script src="jquery-ui-1.11.4/jquery-ui.min.js"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
CSS
body
{
background-color: darkgray;
}
#todoListWrapper
{
width: 960px;
text-align: center;
margin: 0 auto;
padding: 20px 10px 30px;
background: white;
}
.clearfix:after
{
content: "";
display: table;
clear: both;
}
#todoList ul
{
width: 133px;
margin: 0;
padding:0;
position: relative;
display: inline-block;
list-style: none;
}
#todoList li
{
background: none;
padding: 5px;
border: none;
margin: 0;
text-align: left;
font-size: 12px;
}
#todoList li:hover
{
background: #eee;
}
#todoList li.listTitle
{
background: #444;
color: white;
padding: 10px;
text-align: center;
font-size: 14px;
}
#todoList li.listTitle:hover,
#todoList li.listTitle:active
{
cursor: default;
transform: none;
}
#todoList .emptySpace
{
background: #fc3;
border: dashed 1px #777;
height: 10px;
width: 120px;
}
#todoList li.addItem
{
display: none;
position: absolute;
top: 0;
background: none;
padding: 0;
width: 111px;
margin: 5px 4px;
}
#todoList ul:hover li.addItem
{
display: block;
}
#todoList li.addItem input
{
width: 100%;
padding: 4px;
}
#todoList li.addItem :active
{
transform: none;
}
#trash
{
background: rgba(178,73,38,0.7);
height: 300px;
width: 400px;
position: relative;
top: 90px;
left: 35%;
line-height: 300px;
color: white;
font-weight: bold;
font-size: 18px;
text-align: center;
padding: 0;
}
SCRIPT
$(function()
{
$('#todoList ul').sortable({
items: "li:not('.listTitle, .addItem')",
connectWith:"ul",
dropOnEmpty:true,
placeholder: "emptySpace"
});
$('input').keydown(function(e){
if(e.keyCode == 13 && $('input').val()!="")
{
var item = $(this).val();
$(this).parent().parent().append('<li style="font-size:13px;cursor:pointer;display:block;">'+ item + '</li>');
$(this).val("");
}
});
$('#trash').droppable({
drop: function(event, ui)
{
ui.draggable.remove();
}
});
});
Do the following: remove display inline-block , alter the margin and add float:left;
#todoList ul {
//display: inline-block;
float:left;
margin: 0 2px;
}
for the second question do the following:
if(e.keyCode == 13 && $(this).val().trim()!="")
I just stepped through your example. The reason that only your first input box works is because of this line:
if(e.keyCode == 13 && $('input').val()!="")
$('input') returns an array of all the elements matching the selector, meaning all the input boxes. When you ask for the val(), you'll get the value of the first input box in the array, which is "" unless you're typing in the first input box. So nothing happens unless you're on Monday.
You need to get the input box that you're typing into. To do that, change your line to this:
if(e.keyCode == 13 && e.target.value != "")
e.target is the target of the event, which is the input box that you're typing in.

How to center all list's elements to parent div

I am going to add dynamically elements to my block of ul.
I would like to center all list's elements to parent div(brown boder).
For example,
if the resolution of the browser allows you to set two blocks in one row, I would like to center this row in relation to parent div.
I would be very graftefully.
Link to demo
myCode:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
var tab = [2,3,4,5,7,8,9,11,12,13,14,15];
$(document).ready(function(){
$('#godziny').on('click', '.godzina', function(){
//alert(this.attr('class'));
$('.yb').removeClass('yb');
$(this).addClass('yb');
});
$('#getElements').click(function() {
for(i = 0; i < tab.length; ++i) {
alert(tab[i]);
setTimeout(function(i){
$('#godziny').append('<li class="godzina">' + tab[i] + '</li>');
}, i*50);
}
});
});
</script>
<style>
#spisSalonow {
margin: 0 auto;
}
#spisSalonow > div {
padding-top: 15px;
color:red;
}
#wybor_terminu {
border: 1px solid brown;
}
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
border: 1px solid red;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
float: left;
cursor: pointer;
margin-right: 40px;
margin-top: 40px;
/*margin:auto;*/
/*
opacity: 0.4;
filter: alpha(opacity=40);
*/
}
.yb {
background: yellow;
}
</style>
</head>
<body>
<div id="wrapper">
<input type="button" value="get Elements" id="getElements"/>
<section id="content">
<div class="full">
<BR/>
<div id="wybor_terminu" class="center border" style="width: 70%; position: relative;">
<div style="text-align: center"><img src="https://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-05-24.png" alt="Left Arrow" /> <span id="day"> ANY DAY </span> <img src="http://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-06-24.png" alt="Right Arrow" /></div>
<ul id="godziny" style="margin-top: 25px;">
</ul>
</div>
</section>
</div>
</body>
</html>
You can use the CSS flexbox to achieve this. Here is a link to a complete guide on how to use flexbox. I hope this helps.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Add this lines:
CSS
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
/*NEW*/
padding: 0;
width: 100%;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
/*float: left; You don't need this line*/
cursor: pointer;
/*NEW*/
margin:auto;
margin-top: 40px;
}
EDIT
This is only a quick solution with bootstrap maybe it could help you a little bit. jsfiddle
jQuery
In this line I added bootstrap classes:
$('#godziny').append('<li class="godzina col-sm-12 col-md-6">' + tab[i] + '</li>');
This code center your boxes (is not the best solution, but it works):
countBoxes = $('#godziny').width() / 200;
alignBoxes = ($('#godziny').width()-(200*parseInt(countBoxes)))/2;
if(countBoxes >= 2.65){
$('#godziny').css('margin-left', alignBoxes);
} else{
$('#godziny').css('margin-left', 0);
}
If you change the resolution of your screen, click the button to center your boxes again.

classList.toggle in Javascript

I'm trying to assign .hidden to certain elemement when class is not present and remove class .hidden if this class is already assigned to this element. In other words - I just want to toggle class.
I wrote code
var isHidden = document.getElementById("inputSelected").classList.toggle("hidden");
but it doesn't work. But when I console log classList.contains
var isHidden = document.getElementById("inputSelected").classList.contains("hidden");
it returns false - which means, that this class it not assigned. So why it doesn't toggle?
More code:
<!DOCTYPE html>
<html>
<head>
<title>Kalkulator dat</title>
<meta name="description" content="Kalkulator dat. Ile dni minęło od wskazanej daty? Jaka będzie data za daną ilość dni?">
<link rel="StyleSheet" type="text/css" href="style.css">
</head>
<body>
<h1>Kalkulator dat</h1>
<div id="daysPassed">
<h2>Ile pełnych dni minęło?</h2>
<form id=daysPassedForm">
<label for="firstDateDP">Data początkowa:</label>
<input type="date" id="firstDate">
<fieldset>
<input type="radio" id="toToday" name="todayOrSelected">
<label for="toToday">Do dziś</label>
<input type="radio" id="toSelected" name="todayOrSelected">
<label for="toSelected">Do wskazanej daty</label>
<p id="inputSelected">(<input type="date" id="selectedEndDate">)</p>
</fieldset>
<input type="submit" value="Oblicz">
</form>
</div>
<div id="daysPassedResult" class="result">
<p id="daysPassedInfo">Od wskazanej daty minęło x dni</p>
</div>
<div id="dateIndicate">
<h2>Jaka będzie data?</h2>
<form id="dateIndicateForm">
<ul>
<li>
<label for="firstDateDI"><span>Data początkowa:</span></label>
<input type="date" id="firstDateDI">
</li>
<li>
<label for="numberOfDays"><span>Liczba pełnych dni:</span></label>
<input type="number" id="numberOfDays" step="1">
</li>
<li>
<input type="submit" value="Oblicz">
</li>
</ul>
</form>
</div>
<div id="dateIndicateResult" class="result">
<p id="dateIndicateResult">Po x dniach od y będzie</p>
</div>
<script src="script.js"></script>
</body>
</html>
div {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
margin-bottom: 7px;
}
body {
margin: 0 auto;
width: 40%;
background-color: #FFCA51;
}
div {
padding: 5px;
border-radius: 15px;
}
p {
margin: 8px 0 8px 0;
}
ul {
list-style-type: none;
padding: 0;
}
h1 {
text-align: center;}
fieldset {
border: none;
}
input {
margin: 2px;
padding: 1px;
}
span {
width: 115px;
text-align: right;
display: inline-block;
}
#daysPassed {
background-color: #E8A849;
padding-left: 16px;
}
#inputSelected {
margin: 0 0 0 8px;
display: inline-block;
}
#daysPassedResult {
background-color: #FFA75D;
}
#dateIndicate {
background-color: #E87A49;
padding-left: 16px;
margin-top: 20px;
}
#dateIndicateResult {
background-color: #FF6D51;
}
.result {
margin: 8px 0 8px 16px;
padding-left: 12px;
max-width: 50%;
}
.hidden {
display: none;}
function preparePage() {
document.getElementById("inputSelected").classList.toggle("hidden");
document.getElementById("daysPassedResult").classList.toggle("hidden");
document.getElementById("dateIndicateResult").classList.toggle("hidden");
}
window.onload = function() {
preparePage();
};
Right now second and third line of preparePage works, but first (#inputselected) doesn't
DOMTokenList Reference from Mozilla:
toggle ( token ) - removes token from string and returns false. If token doesn't exist it's added and the function returns true
Your code actually works, but it seems that the issue is not caused by the DOMTokenList .toggle() function, but by a CSS id #inputSelected:
#inputSelected {
margin: 0 0 0 8px;
display: inline-block; /* will never let .hidden to actually set the "display: none". */
}
.hidden {
display: none;
}
A simple way to fix it is to define:
.hidden {
display: none !important;
}
or define display: inline-block; in a separate class.
If the problem really is the .toggle, DOMTokenList still has:
.contains
.add
.remove
Otherwise, you can use jQuery or manage the element.className by hand.

Categories