JavaScript Function - javascript

Hello everybody I have this code that I have made alone.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
width: 300px;
height: 300px;
background-color: red;
}
<!DOCTYPE html>
<html>
<body>
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="">DELETE</button>
<div id="myList2">
<div id="test">
</div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>
</body>
</html>
What I want to make is that the red square whenever you are clicking on the ADD button it will be a clone and when you click on the DELETED button that the clone is deleted. Can somebody help me, please?

In addition to missing } as was mentioned in the comments, there was a not-so-obvious problem with finding the <div> to clone. The lastChild was actually a text node containing the \n (newline), after the <div>. It's better to search for <div> by tag:
var itm = document
.getElementById('myList2')
.getElementsByTagName('div')[0];
Since there's only one <div> we can use the zero index to find this first and only one.
And for delete function you can use a similar approach and get the last <div> and remove it.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
}
function myFunction() {
var itm = document.getElementById("myList2").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function deleteFunction() {
var list1 = document.getElementById("myList1");
var divs = Array.from(list1.getElementsByTagName("div"));
// If the number of divs is 3, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 3) {
document.getElementById("button").style.display = "none";
}
var lastDivToDelete = divs[divs.length - 1];
list1.removeChild(lastDivToDelete);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
/* make it smaller so it's easier to show in a snippet */
width: 30px;
height: 30px;
background-color: red;
}
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="deleteFunction()">DELETE</button>
<div id="myList2">
<div id="test"></div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>

Related

how to save toogle class with localstorage. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
var hs = document.getElementById("hs");
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
I fixed your code
if( localStorage.getItem("color") == "black" ) {
{
let element = document.getElementsByTagName("body");
element.classList.toggle("bdark");
}
{
let element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
let element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
let element = document.getElementsByTagName("body");
element.classList="bdark";
}
{
let element = document.getElementById("theader");
element.classList="hdark";
}
{
let element = document.getElementById("sh");
element.classList="shh";
}
{
let hs = document.getElementById("hs");
}
let color;
if(localStorage.getItem("color") != "black") {
color = "black";
localStorage.setItem("color", color)
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>

how to save toogle class with localstorage/cookies. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
var classlist = document.getElementById("body").classList;
clasList.add("bdark");
classList = document.getElementById("theader").classList;
classList.add("hdark");
classList = document.getElementById("sh").classList;
classList.add("shh");
var hs = document.getElementById("hs").classList;
document.getElementById("hs").style.display = "block";
}
function myFunction() {
var classlist = document.getElementById("body").classList;
clasList.toggle("bdark");
classList = document.getElementById("theader").classList;
classList.toggle("hdark");
classList = document.getElementById("sh").classList;
classList.toggle("shh");
var hs = document.getElementById("hs");
if (hs.style.display === "block") {
hs.style.display = "none";
} else {
hs.style.display = "block";
}
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
There are variable spelling mistakes in your code (declared as classlist and used as clasList)
missed closed brackets for the if condition in myFunction.
updated logic for storing color value.
I updated the above changes in your code.
I have added code here also you can check output in it.
Updated code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
if (localStorage.getItem("color") === "black") {
var classlist = document.getElementById("body").classList;
classlist.add("bdark");
classlist = document.getElementById("theader").classList;
classlist.add("hdark");
classlist = document.getElementById("sh").classList;
classlist.add("shh");
document.getElementById("hs").style.display = "block";
}
function myFunction() {
var classlist = document.getElementById("body").classList;
classlist.toggle("bdark");
classlist = document.getElementById("theader").classList;
classlist.toggle("hdark");
classlist = document.getElementById("sh").classList;
classlist.toggle("shh");
var hs = document.getElementById("hs");
if (hs.style.display === "block") {
hs.style.display = "none";
} else {
hs.style.display = "block";
}
if (localStorage.getItem("color") === "black") {
localStorage.setItem("color", "white");
} else {
localStorage.setItem("color", "black");
}
}

How to control execution order when two events are triggered at the same time

This is a simple drop-down menu with input in HTML and pure javascript (no JQuery). I don't want to use the pre-defined HTML list with option tags because i need scroll bars, styling etc.
I hide the list onblur but this event gets triggered before the click on the items list. So the result is that I cant click on the items of the drop-down menu because the list gets hidden before hand.
This is the code:
function showList(){
elem = document.getElementById("list");
elem.className = "unhidden";
}
function hideList(){
elem = document.getElementById("list");
elem.className = "hidden";
}
function showSuccess(){
elem = document.getElementById("successDiv");
elem.innerHTML = "code successful!";
}
.hidden { display: none; }
.unhidden { display: block; }
<html>
<head>
</head>
<body>
<input onfocus="showList();" onblur="hideList();"/>
<div id="list" class="hidden">
click for success
</div>
<div id="successDiv">
</div>
</body>
</html>
The easiest solution is to add a small delay with setTimeout before hiding the element. In the example below i wait a 250 milliseconds before removing the class.
function showList(){
elem = document.getElementById("list");
elem.className = "unhidden";
}
function hideList(){
setTimeout(function() {
elem = document.getElementById("list");
elem.className = "hidden";
}, 250); // Wait 250 milliseconds
}
function showSuccess(){
elem = document.getElementById("successDiv");
elem.innerHTML = "code successful!";
}
.hidden { display: none; }
.unhidden { display: block; }
<html>
<head>
</head>
<body>
<input onfocus="showList();" onblur="hideList();"/>
<div id="list" class="hidden">
click for success
</div>
<div id="successDiv">
</div>
</body>
</html>
EDIT: More robust solution
You can look at the events relatedTarget and if it is inside the list dont close it before clicking on it.
const input = document.querySelector("#input");
const list = document.querySelector("#list");
const listItems = document.querySelectorAll("#list a");
const success = document.querySelector("#successDiv");
input.addEventListener("focus", showList);
input.addEventListener("blur", hideList);
for(const listItem of listItems) {
listItem.addEventListener("click", showSuccess);
}
function showList() {
list.classList.remove("hidden");
}
function hideList(event) {
if(event.relatedTarget?.parentNode !== list) {
list.classList.add("hidden");
}
}
function showSuccess(event) {
success.innerHTML = "code successful!";
// Remove line to keep list open
hideList(event);
}
#list {
display: flex;
flex-direction: column;
}
#list.hidden { display: none; }
<input id="input" />
<div id="list" class="hidden">
click for success
click for more success
click for even more success
</div>
<div id="successDiv">
</div>

refactoring javascript code to create for loop

I am practicing Javascript. I want each link to display something different in the DOM when clicked.
Here is my current Javascript that works.
//used a 'for' loop to hide each 'notes' page
const element = document.querySelectorAll(".notes");
for (let x = 0; x < element.length; x++)
element[x].style.display = 'none';
const html_link= document.getElementById('html-link');
const css_link = document.getElementById('css-link');
const javascript_link = document.getElementById('js-link');
const html_notes = document.getElementById('html-notes');
const css_notes = document.getElementById('css-notes');
const js_notes = document.getElementById('js-notes');
html_link.onclick = function() {
html_notes.style.display = "block";
css_notes.style.display = "none";
js_notes.style.display = "none";
}
css_link.onclick = function() {
css_notes.style.display = "block";
html_notes.style.display = "none";
js_notes.style.display = "none";
}
javascript_link.onclick = () => {
js_notes.style.display = "block";
html_notes.style.display = "none";
css_notes.style.display = "none";
}
How can I refactor it using a for loop? My thinking was for each link clicked, display notes. But I am struggling to figure out how to display the notes div correctly that matches the link clicked. This is what I have started.
const links = document.querySelectorAll('.links')
for (const link of links) {
link.addEventListener('click', function() {
let ref = event.target.parentElement.id.replace('link','notes');
//replaces parent element with id 'notes'
const show = document.getElementById(ref);
//'show' div with new id
})
}
Welcome, fellow newbie! I've taken the liberty of writing the html and very minimal styling as well. This is my first attempt at an answer on stackoverflow.
Please note some features of the code I've added:
'links' class added to all links.
'notes' class added to all notes.
'data-notes' attribute added to all links (with the id of each link's respective notes)
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
</head>
<body>
<div class="outer">
<div id="html-link" data-notes="html-notes" class="links">
<p>html-link</p>
</div>
<div id="css-link" data-notes="css-notes" class="links">
<p>css-link</p>
</div>
<div id="javascript-link" data-notes="javascript-notes" class="links">
<p>javascript-link</p>
</div>
</div>
<div class="outer">
<div id="html-notes" class="notes">
<p>html-notes</p>
</div>
<div id="css-notes" class="notes">
<p>css-notes</p>
</div>
<div id="javascript-notes" class="notes">
<p>javascript-notes</p>
</div>
</div>
<style>
.links {
cursor: pointer;
background: green;
color: white;
padding: 1rem;
margin: 1rem;
}
.notes {
display: none;
background: blue;
color: white;
padding: 1rem;
margin: 1rem;
}
.outer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
margin: 2rem 0;
}
</style>
<script>
const links = document.querySelectorAll('.links');
const notes = document.querySelectorAll('.notes');
for (const link of links) {
link.onclick = function () {
for (const note of notes) {
if (note.id == link.dataset.notes) {
note.style.display = "block";
} else {
note.style.display = "none";
}
}
}
}
</script>
</body>
</html>

show/hide elements and switch between them js

I have two elements that are hidden. When button a is clicked, I would like div a to show. When button b is clicked, I would like div a to close and div b to show.
However, if button a is clicked a second time after being shown, I would like it to hide the div again. Same with button b.
Update:
I was able to get the buttons to toggle properly.
However, upon initial loading, I want them to be hidden, or not visible until the button is clicked.
The following is my current javascript
function openFamily(evt, famName) {
var i, x, y, tablinks;
x = document.getElementsByClassName("family");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("familytablink");
for (i = 0; i < x.length; i++)
document.getElementById(famName).style.display = "block";
}
I have a CSS element:
.container{
display: none;
}
HTML:
<div>
<div>
<button class="familytablink" onclick="openFamily(event,'zep')">Zephaniah</button>
<button class="familytablink" onclick="openFamily(event,'anna')">Anna</button>
</div>
<div id="zep" class="container mainp-2 family">
filler text
</div>
<div id="anna" class="container mainp-2 family">
filler text
</div>
</div>
Here's an exemple of how you can achieve that
var toggleDivById = function (id) {
var div = document.getElementById(id);
if (div.classList.contains('active')) {
return div.classList.remove('active');
}
div.classList.add('active');
}
var handleToggleClick = function (event) {
var targetId = event.target.dataset.target;
toggleDivById(targetId);
}
document.querySelectorAll('.toggle')
.forEach(function(toggle) {
toggle.addEventListener('click', handleToggleClick)
})
.toggable {
width: 50px;
height: 50px;
background-color: crimson;
border: 2px solid tomato;
visibility: hidden;
transition: all 100ms ease-out;
border-radius: 5px;
box-shadow: 1px 1px 2px indianred;
}
.toggable.active {
visibility: visible
}
<button data-target="a" class="toggle">A</button>
<button data-target="b" class="toggle">B</button>
<hr/>
<div id="a" class="toggable">A</div>
<div id="b" class="toggable">B</div>
In jQuery:
<script type="application/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("diva").show();
});
$("#button2").click(function(){
$("diva").hide();
$("divb").show();
});
});
</script>
In JS:
<script type="application/javascript">
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You can use hide and show function in Jquery and use it when a button is clicked something like this :
like
$("selector").click(function(){
$("divid").hide();
$("divid").show();
})

Categories