Javascript event change - javascript

I have the following problem and I am new to JS. I need that every time I select an item of my "select" the event takes the value and shows me the div I need that is in "none". I do not know what I'm doing wrong.
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="#">
<select name="" id="mostrar">
<option>Select</option>
<option value="pos">Posadas</option>
<option value="obe">Obera</option>
<option value="eldo">Eldorado</option>
</select>
</form>
<div id="posadas">Posadas</div>
<div id="obera">Obera</div>
<div id="eldorado">Eldorado</div>
<script src="test.js"></script>
</body>
</html>
JS:
"use strict";
var pos = document.querySelector("#posadas").style.display = "none";
var obe = document.querySelector("#obera").style.display = "none";
var eldo = document.querySelector("#eldorado").style.display = "none";
var mostrar = document.querySelector("#mostrar");
mostrar.addEventListener("change", function{
if(mostrar.value == "pos") {
pos.style.display = "block";
obe.style.display = "none";
eldo.style.display = "none";
console.log(pos);
}else if(mostrar.value == "obe"){
obe.style.display = "block";
pos.style.display = "none";
eldo.style.display = "none";
console.log(obe);
}else{
obe.style.display = "none";
pos.style.display = "none";
eldo.style.display = "block";
console.log(eldo);
}
});

You are setting pos and the other variables incorrectly. As you have it they are all going to be set to the value "none", and not the elements themselves.
Assignments are done right to left so something like:
a = b.something = 3;
will cause both variable a and object b's something property to have the value 3.
You need to split up your lines to assign the element to the variable first then do your style change:
var pos = document.querySelector("#posadas");
var obe = document.querySelector("#obera");
var eldo = document.querySelector("#eldorado");
pos.style.display = "none";
obe.style.display = "none";
eldo.style.display = "none";

Related

How to reload current page without losing added list items?

I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:
`
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
`
but still it doesn't work, I may have used it in the wrong place or wrong way. any help please?
here is my full code:
HTML:
`
<!DOCTYPE html>
<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" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>To Do List</title>
</head>
<body>
<section class="section-center">
<form class="todolist-form">
<h3>To Do List!</h3>
<div class="input-button">
<input type="text" id="items-input" placeholder="e.g. eggs" />
<input
type="button"
class="submit-btn"
onclick="addItems()"
value="Submit"
/>
</div>
<div class="added-items">
<ul id="faves"></ul>
</div>
</form>
</section>
<script src="main.js"></script>
</body>
</html>
`
Javascript:
`
function addItems() {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
var input = document.getElementById("items-input");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
/*********/
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
}
`
What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.
var texts = [];
function addItems() {
var input = document.getElementById("items-input");
createElement(input.value)
input.value = "";
}
function createElement(value) {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
li.innerHTML = value;
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
texts.push(value)
}
window.onbeforeunload = function () {
// Store text array in storage
localStorage.setItem("list", JSON.stringify(texts));
};
window.onload = function () {
// get list grom storage
var list = localStorage.getItem("list");
if (list !== null) {
list = JSON.parse(list)
for (let index = 0; index < list.length; index++) {
const element = list[index];
// create your dom element
createElement(element)
}
}
};
Using an Array to manage the data flow. This will do the job but still a mess.
Try adding event listeners once and outside of your function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list")
};
function addItems() {
...
}
Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};

How to store task in localstorage than onload make it appear in individual tasks

I am trying to make a To Do list but I have encountered a problem with storing it in local storage. I have tried storing the task in a var than it in localStorage but than when a new task is added it overwrites the variable and when I tried to store it in array and than when I tried to retrieve it from array all tasks appeared in a single task div. I want to store the tasks in local storage and have the task be edited, deleted, marked done also for localStorage too. I am providing the code.
<--JS-->
let tasksDiv = document.getElementById("tasks");
let oldTasksDiv = document.getElementById("old-tasks");
let input = document.getElementById('input');
var clear = document.getElementById('clear');
input.value = "What do you have planned?";
addBtn.addEventListener('click' , onclickBtn);
input.addEventListener('keypress' , function(){
if(event.keyCode === 13){
onclickBtn();
}
});
input.addEventListener('click' , function (){
if(input.value === "What do you have planned?"){
input.value ="";
}
})
clear.addEventListener('click' , function (){
input.value ="";
})
function onclickBtn(){
if(input.value.length !== 0){
var tasksName = document.createElement('div');
tasksName.classList.add("tasks-div")
var task = document.createElement('p');
task.innerText = input.value;
task.classList.add("task");
var del = document.createElement('button');
del.classList.add("del");
del.innerHTML = '<i class="fas fa-solid fa-trash"></i>';
var edit = document.createElement('button');
edit.classList.add("edit");
edit.innerHTML = '<i class="fas fa-solid fa-pen-to-square"></i>';
var save = document.createElement('button');
save.classList.add("save");
save.innerHTML = '<i class="fas fa-solid fa-floppy-disk"></i>';
var chkbox = document.createElement('input');
chkbox.classList.add("chkbox")
chkbox.type = "checkbox";
tasksName.appendChild(chkbox);
tasksName.appendChild(task);
tasksName.appendChild(del);
tasksName.appendChild(edit);
tasksName.appendChild(save);
tasksDiv.appendChild(tasksName);
chkbox.addEventListener('click' , function(){
if(chkbox.checked === true){
task.style.textDecoration = "line-through red";
edit.style.display = "none";
save.style.display = "none";
}
else{
task.style.textDecoration = "none";
edit.style.display = "block";
}
})
del.addEventListener('click' , function(){
tasksDiv.removeChild(tasksName);
})
edit.addEventListener('click' , function(){
task.contentEditable = true;
task.focus();
edit.style.display = "none";
save.style.display = "block";
})
save.addEventListener('click' , function(){
if(task.innerHTML === '<br>'){
alert('This task will be deleted');
tasksDiv.removeChild(tasksName);
}
task.contentEditable = false;
task.blur();
edit.style.display = "block";
save.style.display = "none";
})
}
else{
alert("Please enter a task");
}
}
<-- HTML -->
<!DOCTYPE html>
<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>Tasks Keeper</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/resp.css">
<script src="https://kit.fontawesome.com/6bf6193572.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/9b41c17796.js" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div class="brand-div">
<h1><span class="brand">Tasks Keeper</span></h1>
<span class="made-by">Made By Raghav Srvt</span>
</div>
<div class="input-div">
<div class="input-div-clear">
<input type="text" placeholder="What do you have planned?" id="input" value="What do you have planned?">
<i class="fa-solid fa-xmark" id="clear"></i>
</div>
<button type="submit" id="add-btn">Add</button>
</div>
</header>
<div id="tasks">
</div>
<script src = "./app.js"></script>
</body>
</html>
You can insert todos as object into an Array and store it on LocalStorage.
It is a Functionality that makes it Easy for you.
function LsHandling() {
return {
get: function (key) {
const item = localStorage.getItem(key);
if (item) {
return JSON.parse(item);
}
},
set: function (todo, key) {
const item = localStorage.getItem(key);
if (item) {
const itemToArray = [...JSON.parse(item)];
for (data in itemToArray) {
if (itemToArray[data].id === todo.id) {
return;
} else {
itemToArray.push(todo)
localStorage.setItem(key, JSON.stringify(itemToArray));
}
}
} else {
const defaultArray = [todo];
localStorage.setItem(key, JSON.stringify(defaultArray));
}
},
};
}
And you can use it Like This :
for getting the todosArray : LsHandling().get(yourKey)
for setting a todo in todosArray : LsHandling().set(todoObject, yourKey)
Note : for deleting or editing todos , you must define an id for each todo

caroussel not displaying image in JS

i've a problem with my caroussel in JS
He just don't recognize my innerHTML, in fact when i look on the inspector, he don't recognize the on my innerHTML, i've done some research and didn't found anything (showing
<img src = unknown/>.
My img array is an url array not in any folder.
Here's what i already have
function slideShow() {
var counter = 0;
slideShow();
const diapoImages = [
"https://images.unsplash.com/photo-1652044049927-7142ea82c81d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1639718561716-b59d3995d886?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653593349937-1a2a29a614d2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1742&q=80",
"https://images.unsplash.com/photo-1653629154297-d01874fe01c7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653537649117-821e01f707c2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
];
var imgDiv = document.getElementById("header");
if (counter < diapoImages.length) {
var img = diapoImages[counter];
imgDiv.innerHTML = `<img src=${img}/>`;
counter += 1;
}
else {
counter = 0;
}
setTimeout(slideShow, 5000)
}
here's the HTML
<!DOCTYPE html>
<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">
<script src="https://kit.fontawesome.com/c9b7852654.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="css/style.css">
<title>Diaporama</title>
</head>
<body>
<i id = "nav-gauche" class="fa-solid fa-arrow-left-long"></i>
<i id = "nav-droite" class="fa-solid fa-arrow-right-long"></i>
<div class="container">
<h1>Javascript Caroussel</h1>
<h2>Test d'un caroussel en JS</h2>
<div id="header">
</div>
</div>
<script src=""></script>
</body>
</html>
You should create the image tag using document.createElement("img"). Then, you should set the src of image tag. At the end of the function, you should append the image tag into the div tag.
function slideShow() {
var counter = 0;
slideShow();
const diapoImages = [
"https://images.unsplash.com/photo-1652044049927-7142ea82c81d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1639718561716-b59d3995d886?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653593349937-1a2a29a614d2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1742&q=80",
"https://images.unsplash.com/photo-1653629154297-d01874fe01c7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653537649117-821e01f707c2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
];
var imgDiv = document.getElementById("header");
var image = document.createElement("img")
for (var ind in diapoImages)
while ( ind < (diapoImages.length + 1)){
if (counter < diapoImages.length) {
var img = diapoImages[counter];
imgDiv.appendChild(image)
counter += 1;
image.src = img
}
else {
counter = 0;
}
}
}
setTimeout(slideShow, 5000)
I don't know about innerHTML error, but I could see two important points that maybe help you.
The line 3 (slideShow();) causes recursive calls.
Whenever the function is invoked, line 2 (counter = 0;) will reset the value. So the second image will never be rendered.
function slideShow(counter = 0) {
const diapoImages = [
"https://images.unsplash.com/photo-1652044049927-7142ea82c81d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1639718561716-b59d3995d886?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653593349937-1a2a29a614d2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1742&q=80",
"https://images.unsplash.com/photo-1653629154297-d01874fe01c7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
"https://images.unsplash.com/photo-1653537649117-821e01f707c2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80",
];
var imgDiv = document.getElementById("header");
if (counter < diapoImages.length) {
var img = diapoImages[counter];
imgDiv.innerHTML = `<img src=${img}/>`;
counter += 1;
} else {
counter = 0;
}
setTimeout(() => slideShow(counter), 5000)
}
slideShow();
<div id="header"></div>

Change css display of multiple elements using class in javascript

Fairly new to Javascript here. I have a to do list, and I am in the process of adding a feature to Hide all checked items (which have a class .checked).
The idea i have, is to add a display property to the class(that all checked items receive) but how do I do it? Is there any other way for me to be able to add a display property to all of the checked items?
Here's the code (didn't include the other css as it was unnecesary):
//ADD NEW ELEMENT SECTION
function newElement() {
var inputval = document.getElementById('inputnewlist').value;
var li = document.createElement('li');
var lichild = document.createTextNode(inputval);
li.appendChild(lichild);
if (inputval === '') {
alert('you must put something in the textbox!');
} else {
document.getElementById('mylist').appendChild(li);
}
document.getElementById('inputnewlist').value = "";
//REMOVE BUTTON SECTION
var button = document.createElement('button');
var buttonval = document.createTextNode('x');
button.classList.add("exit");
button.appendChild(buttonval);
li.appendChild(button);
var exit = document.querySelectorAll('.exit');
for (b = 0; b < exit.length; b++) {
exit[b].addEventListener('click', removeButtonParent);
}
}//end of create newelement function
var exit = document.querySelectorAll('.exit');
for (z = 0; z < exit.length; z++) {
exit.addEventListener('click', removeButtonParent);
}
function removeButtonParent() {
event.target.parentElement.remove();
}
//ENTER KEY PRESS-BUTTON PRESS
function enterfunction(event) {
var key = document.getElementById('inputnewlist');
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('addbutton').click();
}}
//CHECK BUTTON SECTION
var list = document.querySelector('ul');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
//HIDE CHECKED LIST ITEMS
function hideCheck() {
if (event.target.checked === true) {
var checkLI = document.querySelectorAll('.checked');
checkLI.style.display = "none";
}
else {
var checkliELSE = document.querySelectorAll('.checked');
checkLI.style.display = "";
}
}
.checked {
background-color: darkgrey;
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div id="formcontainer">
<h1 class="title"> To Do List </h1>
<input type="text" name="inputnewlist" id="inputnewlist" placeholder="Add thing to do.." onkeydown="enterfunction(event)">
<button onclick="newElement()" class="addbutton" id="addbutton">Add</button>
</div>
<ul id="mylist">
</ul>
<input type="checkbox" id="hidecheck" onchange="hideCheck()"> <label for="hidecheck"> Hide the checked list items</label>
<script src="scripts.js"></script>
</body>
You can try the following code by adding the style 1 by 1.
function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}

How do i change my text everytime when i click on the link in JavaScript?

I would like to create a text generator however when i click on the link it can only generate some sample text which is stored in array once. I have tried using more than one string but i cant get it to work. Here is the code:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Text generate 2 - copy</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
Generate
<h1 id="head"></h1>
<p id="para"></p>
<script src="js/script.js"></script>
</body>
</html>
JS:
var heading = document.getElementById('head');
var paragraph = document.getElementById('para');
var head = ["Sample heading one"];
var para = ["Sample paragraph one"];
document.getElementById("link").onclick = function visible() {
if (heading.style.display = "none")
{
heading.style.display = "block";
}
else
{
heading.style.display = "block";
}
if (paragraph.style.display = "none")
{
paragraph.style.display = "block";
}
else
{
paragraph.style.display = "block";
}
heading.innerHTML = head;
paragraph.innerHTML = para;
}
JS Bin

Categories

Resources