I have many <p>s with the same function.
document.getElementById("minus").onclick = function() {
functionHide()
};
function functionHide() {
document.getElementById("plus").style.display = "block";
document.getElementById("minus").style.display = "none";
}
document.getElementById("plus").onclick = function() {
functionShow()
};
function functionShow() {
document.getElementById("plus").style.display = "none";
document.getElementById("minus").style.display = "block";
}
#plus {
display: none;
cursor: pointer;
}
#minus {
cursor: pointer;
}
.floatright {
float: right
}
.w50 {
width: 50%;
text-align: center;
}
<div class="w50">
<p>What paperwork do I need to complete to file for divorce ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
<p>How do I change my custody and suport orders ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
</div>
When I click on the first minus ( "-" ) it works correctly.
but for the second, it doesn't work.
I want to know how can I automatically chain for all others divs. they have the same typing code.
Also, I would know how can I change the last element (" - ") when an another + is clicked?
Here is a preview of what I want to do
And a fiddle: https://jsfiddle.net/khrismuc/prsebqg3/15/
You are using duplicate IDs, which is a no-no. Here is an example using classes and .querySelectorAll.
var minuses = document.querySelectorAll(".minus");
var pluses = document.querySelectorAll(".plus");
minuses.forEach(function(minus) {
minus.addEventListener('click', functionHide);
});
pluses.forEach(function(plus) {
plus.addEventListener('click', functionShow);
});
function functionHide() {
pluses.forEach(function(plus) {
plus.style.display = "block";
});
minuses.forEach(function(minus) {
minus.style.display = "none";
});
}
function functionShow() {
pluses.forEach(function(plus) {
plus.style.display = "none";
});
minuses.forEach(function(minus) {
minus.style.display = "block";
});
}
You can modify for your particular uses.
Your logic needs to be slightly more complex:
var current = -1;
function handleClick(clicked) {
$(".w50 p").removeClass("active").find("span").text("+");
$("#box p").hide();
if (current === clicked) {
current = -1;
return;
}
current = clicked;
$(".w50 p").eq(current).addClass("active").find("span").text("-");
$("#box p").eq(current).show();
}
$(document).ready(function() {
$(".w50 p").each(function(i, el) {
$(this).append($("<span>").text("+"));
$(this).click(function() {
handleClick(i);
});
});
$(".w50 p").eq(0).click();
});
.w50 {
width: 80%;
text-align: center;
}
.w50 p {
cursor: pointer
}
.w50 p.active {
color: orange
}
.w50 p span {
float: right;
width: 1em;
display: inline-block;
}
#box {
background-color: orange;
margin: 20px;
min-height: 6em;
}
#box p {
display: none;
padding: 1em
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w50">
<p>What paperwork do I need to complete to file for divorce?</p>
<p>How do I change my custody and support orders?</p>
</div>
<div id="box">
<p>Paperwork description</p>
<p>Custody description</p>
</div>
Related
Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated
To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>
Is there a more dynamic way to hide/show divs that are identical in structure with no identifiers?
Click to show
I'm some stuff
<div class="setup" onclick="show(1)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
function show(elem) {
var p = document.getElementsByClassName("hidden");
if (p[elem] != undefined) {
if (p[elem].style.display == "none") {
p[elem].style.display = "block";
} else {
p[elem].style.display = "none";
}
}
}
http://jsfiddle.net/ba7yfmz6/29/
Use this:
<div class="setup" onclick="show(this)">
JavaScript:
function show(elem) {
var paragraph = elem.querySelector(".hidden");
if (paragraph.style.display == "none") {
paragraph.style.display = "block";
} else {
paragraph.style.display = "none";
}
Hopefully this helps!
Yes, there is a way!
You can get all your elements, iterate them via forEach and assign your function to their onclick property:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = showElem;
});
Doing this, you can get rid of the onlick on your HTML elements.
To get their child element (the one you want to hide / show, obviously), your show() function can look like this:
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
And all together:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = show;
});
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
JS Fiddle: http://jsfiddle.net/ba7yfmz6/38/
More info:
forEach
querySelectorAll()
You can use this.
Also, since the div doesn't have a style attribute, checking for style.display === 'none' would always be false on the first click; it would set the the style.display to none. Checking for the computed style would show the hidden element on first click.
function show(el) {
const toggle = el.querySelector('.hidden');
toggle.style.display = window.getComputedStyle(toggle).display === 'none' ? 'block' : 'none';
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
<div class="setup" onclick="show(this)">
Then the JavaScript:
function show(that) {
var hiddenElements = that.getElementsByClassName('hidden');
for (var i = 0; i < hiddenElements.length; i++) {
var style = hiddenElements[i].style;
style.display = style.display == "block" ? "none" : "block";
}
}
I'm trying to make a Single Page Application with pure JavaScript (no additional frameworks or libraries). The problem is that the values I add to the TODO list are not storing in the localStorage (and are not showing).
I would appreciate any help with that task.
How can I simplify the code? (without using any additional libraries and frameworks (ex.jquery etc.))
Here is my code:
let inputTask = document.getElementById('toDoEl');
let editTask = document.getElementById('editTask');
let checkTask = document.getElementById('list');
let emptyList = document.getElementById('emptyList');
let items = [];
let id = [];
let labelToEdit = null;
const empty = 0;
let pages = ['index', 'add', 'modify'];
load();
function load() {
items = loadFromLocalStorage();
id = getNextId();
items.forEach(item => renderItem(item));
}
function show(shown) {
location.href = '#' + shown;
pages.forEach(function(page) {
document.getElementById(page).style.display = 'none';
});
document.getElementById(shown).style.display = 'block';
return false;
}
function getNextId() {
for (let i = 0; i<items.length; i++) {
let item = items[i];
if (item.id > id) {
id = item.id;
}
}
id++;
return id;
}
function loadFromLocalStorage() {
let localStorageItems = localStorage.getItem('items');
if (localStorageItems === null) {
return [];
}
return JSON.parse(localStorageItems);
}
function saveToLocalStorage() {
localStorage.setItem('items', JSON.stringify(items));
}
function setChecked(checkbox, isDone) {
if (isDone) {
checkbox.classList.add('checked');
checkbox.src = 'https://image.ibb.co/b1WeN9/done_s.png';
let newPosition = checkTask.childElementCount - 1;
let listItem = checkbox.parentNode;
listItem.classList.add('checked');
checkTask.removeChild(listItem);
checkTask.appendChild(listItem);
} else {
checkbox.classList.remove('checked');
checkbox.src = 'https://image.ibb.co/nqRqUp/todo_s.png';
let listItem = checkbox.parentNode;
listItem.classList.remove('checked');
}
}
function renderItem(item) {
let listItem = document.getElementById('item_template').cloneNode(true);
listItem.style.display = 'block';
listItem.setAttribute('data-id', item.id);
let label = listItem.querySelector('label');
label.innerText = item.description;
let checkbox = listItem.querySelector('input');
checkTask.appendChild(listItem);
setChecked(checkbox, item.isDone);
emptyList.style.display = 'none';
return listItem;
}
function createNewElement(task, isDone) {
let item = { isDone, id: id++, description: task };
items.push(item);
saveToLocalStorage();
renderItem(item);
}
function addTask() {
if (inputTask.value) {
createNewElement(inputTask.value, false);
inputTask.value = '';
show('index');
}
}
function modifyTask() {
if (editTask.value) {
let item = findItem(labelToEdit);
item.description = editTask.value;
labelToEdit.innerText = editTask.value;
saveToLocalStorage();
show('index');
}
}
function findItem(child) {
let listItem = child.parentNode;
let id = listItem.getAttribute('data-id');
id = parseInt(id);
let item = items.find(item => item.id === id);
return item;
}
// Chanhe img to checked
function modifyItem(label) {
labelToEdit = label;
editTask.value = label.innerText;
show('modify');
editTask.focus();
editTask.select();
}
function checkItem(checkbox) {
let item = findItem(checkbox);
if (item === null) {
return;
}
item.isDone = !item.isDone;
saveToLocalStorage();
setChecked(checkbox, item.isDone);
}
function deleteItem(input) {
let listItem = input.parentNode;
let id = listItem.getAttribute('data-id');
id= parseInt(id);
for (let i in items) {
if (items[i].id === id) {
items.splice(i, 1);
break;
}
}
if (items.length === empty) {
emptyList.style.display = 'block';
}
saveToLocalStorage();
listItem.parentNode.removeChild(listItem);
}
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h2, li, #notification {
text-align: center;
}
h2 {
font-weight: normal;
margin: 0 auto;
padding-top: 20px;
padding-bottom: 20px;
}
#root {
width: 400px;
height: 550px;
margin: 0 auto;
position: relative;
}
#root>ul {
display: block;
}
#addButton {
display: block;
margin: 0 auto;
}
.checkbox, .delete {
height: 24px;
bottom: 0;
}
.checkbox {
float: left;
}
.delete {
float: right;
}
ul {
margin: 20px 30px 0 30px;
padding-top: 20px;
padding-left: 20px;
text-align: center;
}
#toDoEl {
width: 50%;
}
li {
width: 100%;
list-style: none;
box-sizing: border-box;
display: flex;
justify-content: space-between;
align-items: center;
margin: 15px auto;
}
label {
margin: 0 auto;
text-align: justify;
text-justify: inter-word;
}
label:hover {
cursor: auto;
}
li.checked {
background-color: gray;
}
span.button {
cursor: pointer;
}
#add, #modify {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homework 12 - Simple TODO List</title>
<link rel="stylesheet" href="./assets/styles.css">
</head>
<body>
<div id="root">
<!--Main page-->
<div id="index">
<h2>Simple TODO Application</h2>
<button class="button" id="addButton" onclick="show('add')">Add New Task</button>
<p id="emptyList">TODO is empty</p>
<ul id="list">
<li id="item_template" style="display: none">
<input class="checkbox" type="image" alt="checkbox" src="https://image.ibb.co/nqRqUp/todo_s.png" onclick="checkItem(this)">
<label onclick="modifyItem(this)"></label>
<input id="delete" class="delete" type="image" alt="remove" src="https://image.ibb.co/dpmqUp/remove_s.jpg" onclick="deleteItem(this)">
</li>
</ul>
</div>
<!--Add page-->
<div id="add">
<h2>Add Task</h2>
<input type="text" id="toDoEl">
<button class="button cancel" onclick="show('index')">Cancel</button>
<button class="button save" onclick="addTask()">Save changes</button>
</div>
<!--Modify page-->
<div id="modify">
<h2>Modify item</h2>
<input type="text" id="editTask">
<button class="button cancel" onclick="show('index')">Cancel</button>
<button class="button save" onclick="modifyTask()">Save changes</button>
</div>
</div>
<script src="./src/app.js"></script>
</body>
</html>
Your code does appear to work. If you console.log(JSON.parse(localStorageItems)) right above line 49 in the loadFromLocalStorage function, it shows as expected in the console. Also, upon refreshing the items persist.
If what you mean is that you're checking localStorage and you don't see the items, it might be that you're looking at the preview version of localStorage. (I'm assuming you're using Chrome.) Hover over the top of the empty section and pull down, this should reveal the values stored. If you click on one, it should show in the preview section. I think this was a Chrome dev tools UI change recently implemented.
I checked your code in Codepen and it works.
Trying to add a random class to two classes (.left & .right) but with a rule of the two random divs cannot appear at the same time
JS:
$(document).ready(function(){
var classes = ['random-1','random-2', 'random-3']; //add as many classes as u want
var randomnumber = Math.floor(Math.random()*classes.length);
$('.left').addClass(classes[randomnumber]);
});
HTML:
<div class="left">
Left
</div>
<div class="right">
Right
</div>
.left {
background: blue;
height: 100vh;
width: 50%;
float: left;
position: relative;
}
.right {
background: red;
height: 100vh;
width: 50%;
float: right;
}
.random-1 {
background: orange;
}
.random-2 {
background: yellow;
}
.random-3 {
background: pink;
}
.random-4 {
background: green;
}
.random-5 {
background: blueviolet;
}
Ideal result would be
<div class="left random-1">
Left
</div>
<div class="right random-4">
Right
</div>
https://codepen.io/anon/pen/OOJaqL
You can use a while loop that iterates until two random and unique classes have been chosen.
function getRandomClass() {
let classes = ['random-1','random-2', 'random-3'];
let index = Math.floor(Math.random() * classes.length);
return classes[index];
}
$(document).ready(function() {
let leftClass = null;
let rightClass = null;
while (leftClass == rightClass) {
leftClass = randomClass();
rightClass = randomClass();
}
$('.left').addClass(leftClass);
$('.right').addClass(rightClass);
});
Add the .random-* class to the left div, only when the right div does not have this class.
var rightHasClass = $('.right').hasClass(classes[randomnumber]);
if( ! rightHasClass){
$('.left').addClass(classes[randomnumber]);
}
var leftHasClass = $('.left').hasClass(classes[randomnumber]);
if( ! leftHasClass){
$('.right').addClass(classes[randomnumber]);
}
So I made a bunch of divs stacked on each other, and I want each div to change its background color whenever its hover, but that's not what happens
When I hover an item its background color should change to green,
but it doesn't work even that I wrote div.oldiv:hover{background-color: #48FF0D;}
The problem is probably in CSS code.
Here is a snippet :
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;}
div.oldiv:hover{
background-color: #48FF0D;
}
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l{
float: right;
}
<body>
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
window.onload = function (){
document.getElementById("bigdiv").innerHTML = b;
document.getElementById("bigdiv2").innerHTML = k;
}
function utd(a){
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0){
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
}else{
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
</div>
<div id="bigdiv2">
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
</body>
Don't word about all the Javascript, its just to generate elements and adding them to HTML
I have no idea what the purpose of this code is, but I think I have fixed it..... Whatever it is :P
Your #bigdiv and #bigdiv2 percentage height were not working because the height of the document wasn't 100%. So I just added html, body {height:100%;} to fix that.
/* code added START */
html, body {
height:100%;
}
div.oldiv:hover {
background-color: #48FF0D!important;
}
/* code added END */
body{
background-color: #48FF0D;
}
#bigdiv {
height: 90%;
width: 100%;
}
.oldiv {
height: 0.390625%;
width: 100%;
}
/* div.oldiv:hover{background-color: #48FF0D;} */
#bigdiv2 {
height: 0;
width: 100%;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
cursor: pointer;
}
.uptodown {
background-color: #e7e7e7;
color: black;
}
.uptodown:hover {
background: #ddd;
}
.l {
float: right;
}
<script>
var b = "",k = "",a,q,d;
for(a = 0;a<=256;a++){
d =" <div id=\"du\" class=\"oldiv\" style=\"background-color: rgb("+a+","+a+","+a+");\"></div>";
q =" <div id=\"du\" class=\"oldiv\" style=\"background-color:rgb("+(256-a)+","+(256-a)+","+(256-a)+");\"></div>";
b = b+"\n"+d;
k = k+"\n"+q;
}
function utd(a) {
var bigdiv = document.getElementById("bigdiv");
var bigdiv2 = document.getElementById("bigdiv2");
if(a == 0) {
bigdiv.style.height = "0";
bigdiv2.style.height= "90%";
} else {
bigdiv.style.height = "90%";
bigdiv2.style.height= "0";
}
}
</script>
<div id="bigdiv">
<script>document.write(b);</script>
</div>
<div id="bigdiv2">
<script>document.write(k);</script>
</div>
<div>
<button class="btn uptodown" onclick="utd(0)">white to black</button>
<button class="btn uptodown l" onclick="utd(1)">black to white</button>
</div>
Well, there is no use of Javascript here. I'm not able to understand what problem you're facing but refer here : https://www.w3schools.com/cssref/sel_hover.asp
CSS already has property of hover and can be used like element:hover {your properties inside like whatever event has to be happened on hover}. There is no need to use JS here. Hope this helps.
UPDATE:
I would also suggest you to follow good practice of writing JS code and CSS code in a separate file not in a HTML file.