I'm struggling with something that might be a basic thing. The event bound to the button (code below) only works once. After that, nothing seems to happen again on button click. I have treated the wanted behavior in the first if statement of the blur function, but since it does not execute a second time, it seems purposeless.
<button type="button" id="openModal">Open Modal</button>
<p>some text</p>
<script>
class ModalContent{
constructor(title, text){
this.title = title;
this.text = text;
}
}
var modalObject = new ModalContent("this is the modal title", "and this is its inner text");
var openModal = document.querySelector("#openModal");
var body = document.querySelector("body");
var lorem = document.querySelector("p");
openModal.addEventListener('click', blur);
function blur(event){
if(body.querySelector("#modal") != null){
var modal = body.querySelector("#modal");
console.log(modal);
modal.style.display = "flex";
}
body.innerHTML = '<div id="initial-content">' + body.innerHTML + '</div>'
var initialContent = body.querySelector("#initial-content");
initialContent.style.filter = "blur(5px)";
// Replaced this, that does NOT work as desired in JS
// body.innerHTML = body.innerHTML + '<div id="modal"></div>';
// With this:
initialContent.insertAdjacentHTML('afterend', '<div id="modal"></div>');
var modal = body.querySelector("#modal");
modal.innerHTML =
'<h2 id="modal-title">' + modalObject.title + "</h2>" + '<div id="modal-text">' + modalObject.text + "</div>"
+ '<button id="close-modal">Close this</button>';
modal.querySelector("#modal-text").style.marginBottom = "20px";
modal.style =
"display: flex; flex-direction: column; background-color: rgba(255, 255, 255, 0.8); border: 1px solid #ccc; border-radius: 10px; box-shadow: 0px 1px 8px #ddd; color: black; text-align: center; padding: 60px; position: fixed; top: calc(50% - 206px); /* it's the raw height value */ left: calc(50% - 166.675px); * it's the raw width/2 value *";
var closeModal = modal.querySelector("#close-modal");
closeModal.addEventListener('click', closeModalFunction);
function closeModalFunction(event){
modal.style.display = "none";
if(initialContent.style.filter.search("blur") != -1)
initialContent.style.filter = "unset";
}
console.log("1st");
}
</script>
</body>
When you set the innerHTML of the body, all the event listeners on the elements get removed. Instead of adding elements to the body inside the event listener, initially put all the elements in the HTML and show or hide them as necessary.
class ModalContent {
constructor(title, text) {
this.title = title;
this.text = text;
}
}
var modalObject = new ModalContent("this is the modal title", "and this is its inner text");
var openModal = document.querySelector("#openModal");
var body = document.querySelector("body");
var lorem = document.querySelector("p");
openModal.addEventListener('click', blur);
function blur(event) {
if (body.querySelector("#modal") != null) {
var modal = body.querySelector("#modal");
//console.log(modal);
modal.style.display = "flex";
}
var initialContent = document.getElementById('initial-content');
initialContent.style.filter = "blur(5px)";
var modal = body.querySelector("#modal");
modal.innerHTML =
'<h2 id="modal-title">' + modalObject.title + "</h2>" + '<div id="modal-text">' + modalObject.text + "</div>" +
'<button id="close-modal">Close this</button>';
modal.querySelector("#modal-text").style.marginBottom = "20px";
modal.style =
"display: flex; flex-direction: column; background-color: rgba(255, 255, 255, 0.8); border: 1px solid #ccc; border-radius: 10px; box-shadow: 0px 1px 8px #ddd; color: black; text-align: center; padding: 60px; position: fixed; top: calc(50% - 206px); /* it's the raw height value */ left: calc(50% - 166.675px); * it's the raw width/2 value *";
var closeModal = modal.querySelector("#close-modal");
closeModal.addEventListener('click', closeModalFunction);
function closeModalFunction(event) {
modal.style.display = "none";
initialContent.style.filter = "unset";
}
//console.log("1st");
}
<div id="initial-content">
<button type="button" id="openModal">Open Modal</button>
<p>some text</p>
</div>
<div id="modal"></div>
Related
I have a page which contains the following code.
<style>
.objects {display: inline-table; width: 180px; height: 180px; border-radius: 50%; transition: transform .4s;}
.objects:hover { transform: scale(1.1); }
.objects:after {content: ""; position: absolute; top: 0; bottom: 0; left: 0; right: 0; width:180px; height: 180px; z-index: -1; background-color: rgba(255, 255, 255, 0.4);}
#media screen and (max-width: 500px) {
.objects, .objects:after { width: 20vw; height: 20vw;}
}
.objects p { text-align: center; vertical-align: middle; display: table-cell; visibility: hidden; color: black; z-index: 100; position: relative;}
#object1{background-color: brown;}
#object2{background-color: red;}
#object3{background-color: yellow;}
#object4{background-color: blue;}
#object5{background-color: green;}
#object6{background-color: black;}
</style>
<div style="display: flex; justify-content: space-around;margin-top:50px;margin-bottom:100px;">
<div id="object1" class="objects" onmouseover="nomeIn(this)" onmouseout="nomeOut(this)" >
<p>brick brown</p>
</div>
<div id="object2" class="objects" onmouseover="nomeIn(this)" onmouseout="nomeOut(this)" >
<p>brick red</p>
</div>
<div id="object3" class="objects" onmouseover="nomeIn(this)" onmouseout="nomeOut(this)">
<p>brick melange</p>
</div>
</div>
<script>
function nomeIn(object){
let selettore = "#" + object.id + " p";
document.querySelector(selettore).style.visibility = "visible";
}
function nomeOut(object){
let selettore = "#" + object.id + " p";
document.querySelector(selettore).style.visibility = "hidden";
}
</script>
This page works properly, as you can see in the following JSFiddle:
However, for some reasons, one of the plugins I have in my site keeps erasing all the events from the html code, so I can't use "onmouseover" and "onmouseout".
Without these events in the html, I can't call the function and I should write a different JS code, which would be similar to this:
document.querySelector(".objects").onmouseover = function nomeIn(){
let selector = "#" + this.id + " p";
document.querySelector(selector).style.visibility = "visible";
}
document.querySelector(".objects").onmouseout = function nomeOut(){
let selector = "#" + this.id + " p";
document.querySelector(selector).style.visibility = "hidden";
}
However, in this case, the mouseover would work only with the first circular element (the text would appear only in the first circle): JSFiddle
What am I doing wrong?
Thank you for your help.
Because in the second code, you are using document.querySelector to select the .objects divs. This function always return the first element encountered. To solve this, you could use the document.querySelectorAll function and iterate through each element:
[ ...document.querySelectorAll(".objects") ].forEach(element => {
element.onmouseover = function () {
let selector = "#" + this.id + " p";
document.querySelector(selector).style.visibility = "visible";
}
element.onmouseout = function () {
let selector = "#" + this.id + " p";
document.querySelector(selector).style.visibility = "hidden";
}
});
I used javascript to drag&drop multi files. than I am showing those images. Below is fully runable with no errors
Need help with: I want ability to remove those image as well. Please take a look at attached image below, I want to create [x] buttons at top right on image. if click on [x] than it will remove image depending on which [x] you click. close is in drop function below
below is my javascript so far. need help in drop function
var dropZone = document.getElementById('dropZone');
var details = document.querySelector('#imgDetail');
///////////
// dragover
///////////
dropZone.addEventListener('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
document.getElementById('dropZone').classList.add("hoverActive");
});
/////////////
//drag leave
/////////////
dropZone.addEventListener('dragleave', function (e) {
document.getElementById('dropZone').classList.remove("hoverActive");
});
////////////
// drop file
////////////
dropZone.addEventListener('drop', (e) => {
document.getElementById('dropZone').classList.remove("hoverActive");
document.getElementById('BackgroundText').style.visibility = "hidden";
e.stopPropagation();
e.preventDefault();
details.innerHTML = '';
var files = e.dataTransfer.files;
Object.values(files).forEach((file) => {
var reader = new FileReader();
reader.onloadend = () => {
//display image
var img = document.createElement('img');
img.src = reader.result;
img.style.paddingRight = 5;
img.width = 150;
img.height = 150;
img.border = 2;
var div = document.getElementById('imageHold')
div.appendChild(img);
//create button
div.innerHTML += '<button id="btn" name="btn">X</button>';
//display file name
details.innerHTML += `<p>Name: ${file.name}<p>';
//details.innerHTML += <p>Size: ${bytesToSize(file.size)}</p>`;
};
reader.readAsDataURL(file);
});
});
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
#dropZone
{
border: 2px dashed gray;
height: 200px;
width: auto;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#dropZone header{
font-size: 20px;
font-weight:bold;
}
.hoverActive{
border: 2px dashed darkred !important;
}
<br /><br />
<div class="container">
<div class="row">
<div>
<div id="dropZone">
<div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
<header id="BackgroundText">Drag & Drop to Upload File</header>
<div id="imageHold" style="float:left;">
</div>
</div>
</div>
</div>
</div>
<div id="imgDetail">test</div>
html code
var dropZone = document.getElementById('dropZone');
var details = document.querySelector('#imgDetail');
///////////
// dragover
///////////
dropZone.addEventListener('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
document.getElementById('dropZone').classList.add("hoverActive");
});
/////////////
//drag leave
/////////////
dropZone.addEventListener('dragleave', function (e) {
document.getElementById('dropZone').classList.remove("hoverActive");
});
////////////
// drop file
////////////
dropZone.addEventListener('drop', (e) => {
document.getElementById('dropZone').classList.remove("hoverActive");
document.getElementById('BackgroundText').style.visibility = "hidden";
e.stopPropagation();
e.preventDefault();
details.innerHTML = '';
var files = e.dataTransfer.files;
Object.values(files).forEach((file) => {
var reader = new FileReader();
reader.onloadend = () => {
//create frame elem section
let dv = document.createElement('div');
dv.style.cssText = `
display: inline-block;
position: relative;
width: 150px;
height: 150px;
border: 1px #ddd solid;
margin-right: 5px;
`;
//create image elem
var img = document.createElement('img');
img.src = reader.result;
// optional 100%
// img.style.width = "100%";
img.style.width = "150px";
img.style.height= "150px";
//add img to frame
dv.append(img);
//create btn remove
let btn = document.createElement('button');
btn.innerHTML = "x";
btn.style.cssText = `
position: absolute;
right: 2px;
top:2px;
`;
//add btn to frame
dv.append(btn);
//set frame to target elem
document.getElementById('imageHold').append(dv);
//set event btn and exec remove frame
btn.addEventListener('click', e => {
e.target.parentElement.remove();
});
//display file name
details.innerHTML += `<p>Name: ${file.name}<p>';
//details.innerHTML += <p>Size: ${bytesToSize(file.size)}</p>`;
};
reader.readAsDataURL(file);
});
});
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
#dropZone
{
border: 2px dashed gray;
height: 200px;
width: auto;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#dropZone header{
font-size: 20px;
font-weight:bold;
}
.hoverActive{
border: 2px dashed darkred !important;
}
<br /><br />
<div class="container">
<div class="row">
<div>
<div id="dropZone">
<div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
<header id="BackgroundText">Drag & Drop to Upload File</header>
<div id="imageHold" style="float:left;">
</div>
</div>
</div>
</div>
</div>
<div id="imgDetail">test</div>
Demo Page
HTML:
div.innerHTML += '<button id="btn" name="btn" onclick=removeImage_and_btn(this)>X</button>';
You could use previousSibling to get the previous element
JS:
function removeImage_and_btn(el){
if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back
var el = el.previousSibling;
}
if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
el.previousSibling.remove();
el.remove();
}
}
I have this program that can make closables dynamically. When the user clicks on a created closable an input box and a button are displayed in the content of the closable. The user can then input text into the textbox and then press the button. Then the users text will be displayed in the selected closable content.
Everything works, fine, except for when I try to display the users input in the selected closables content.
Here's what's happening:
When the user inputs something in the text box it's append to the closables content:
The text is only displayed in the closable content after I close the selected closable:
Why isn't the users input being displayed in the selected closable after I click the add task button?
Here is my full code:
var currentClosable;
var currentContent;
function selectedColl(){
document.getElementById("inputTaskDiv").style.display = "block";
currentClosable = event.target;
currentContent = currentClosable.nextElementSibling;
var inputTaskDiv = document.getElementById("inputTaskDiv");
currentContent.append(inputTaskDiv);
}
var taskCounter = 0;
function addTask() {
var text = document.getElementById("taskInput").value;
// create a new div element and give it a unique id
var newTask = $("<input type='checkbox'><label>"+ text + "</label><br>");
newTask.id = 'temp' + taskCounter;
taskCounter++
// and give it some content
var newContent = document.createTextNode(text);
$(currentContent).append(newTask); //Why isn't it being displayed??
console.log("appended");
}
var elementCounter = 0;
var elementCounterContent = 0;
var text;
function addElement() {
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = $("<button class='collapsible' onclick='selectedColl()'></button>").text(text);
var newContentOfDiv = $("<div class='content'></div>");
newDiv.id = 'temp' + elementCounter;
newContentOfDiv.id = 'content' + elementCounterContent;
newDiv.classList = "div";
elementCounter++
elementCounterContent++
// and give it some content
var newContent = document.createTextNode(text);
// add the newly created element and its content into the DOM
document.getElementById("input").value = " ";
$("body").append(newDiv, newContentOfDiv);
newDiv.click(function() {
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="input" type="text"><button onclick="addElement()">Add</button>
<div id="inputTaskDiv" style="display:none">
<input id="taskInput" type="text"><button onclick="addTask()">Add Task</button>
</div>
The changes made are in CSS and JS.
In CSS you can see which lines are commented on style ".content": max-height and overflow
The change in JS is:
I changed content.style.maxHeight with this content.style.display
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.display === 'block') {
content.style.display = 'none';
} else {
content.style.display = 'block';
}
Example:
var currentClosable;
var currentContent;
function selectedColl() {
document.getElementById("inputTaskDiv").style.display = "block";
currentClosable = event.target;
currentContent = currentClosable.nextElementSibling;
var inputTaskDiv = document.getElementById("inputTaskDiv");
currentContent.append(inputTaskDiv);
}
var taskCounter = 0;
function addTask() {
var text = document.getElementById("taskInput").value;
// create a new div element and give it a unique id
var newTask = $("<input type='checkbox'><label>" + text + "</label><br>");
newTask.id = 'temp' + taskCounter;
taskCounter++
// and give it some content
var newContent = document.createTextNode(text);
$(currentContent).append(newTask); //Why isn't it being displayed??
console.log("appended");
}
var elementCounter = 0;
var elementCounterContent = 0;
var text;
function addElement() {
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = $("<button class='collapsible' onclick='selectedColl()'></button>").text(text);
var newContentOfDiv = $("<div class='content'></div>");
newDiv.id = 'temp' + elementCounter;
newContentOfDiv.id = 'content' + elementCounterContent;
newDiv.classList = "div";
elementCounter++
elementCounterContent++
// and give it some content
var newContent = document.createTextNode(text);
// add the newly created element and its content into the DOM
document.getElementById("input").value = " ";
$("body").append(newDiv, newContentOfDiv);
newDiv.click(function () {
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.display === 'block') {
content.style.display = 'none';
} else {
content.style.display = 'block';
}
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active,
.collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
/* max-height: 0; */
/* overflow: hidden; */
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="input" type="text"><button onclick="addElement()">Add</button>
<div id="inputTaskDiv" style="display:none">
<input id="taskInput" type="text"><button onclick="addTask()">Add Task</button>
</div>
I am working on a simple To-Do list project. In this project you are able to add a task and once the user presses submit the task is shown along with a checkbox. When you click the checkbox, it's supposed to show an alert and make the tasks style decoration line-through.
I've tried many ways to accomplish this. The first way I tried work however it only worked on one task and for the others, it showed an error. I also tried making it work with an if statement but it's just showing the same error. I've tried switching a lot of things around (that's why my code looks so messy) but it just won't work.
var name = prompt("Please Enter Your Name :)");
document.write('<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function () {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function () {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function () {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks");
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'checked();'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function checked() {
if (check.onclick == true) {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
}
body {
background-image: url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color: white;
width: 700px;
height: 400px;
position: absolute;
left: 325px;
top: 150px;
}
#greet {
position: absolute;
left: 445px;
top: 150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color: blue;
font-weight: bold;
position: absolute;
left: 625px;
top: 230px;
}
#b {
background-image: linear-gradient(#2980B9, #6DD5FA, #fff);
color: black;
border-color: white;
text-weight: bold;
width: 70px;
height: 50px;
position: absolute;
left: 625px;
top: 260px;
}
.To-Do {
width: 100%;
height: 100%;
position: absolute;
top: 0;
display: flex;
justify-content: center;
align-items: center;
display: none;
z-index: 1;
}
.modal-content {
width: 500px;
height: 300px;
border-radius: 10px;
position: relative;
background-color: purple;
}
.close {
position: absolute;
top: 0;
right: 14px;
font-size: 32px;
transform: rotate(45deg);
cursor: pointer;
}
#aat {
background-color: white;
font-weight: bold;
}
h2 {
position: absolute;
left: 590px;
top: 305px;
border-bottom: 5px solid blue;
}
p {
font-weight: bold;
position: relative;
left: 590px;
top: 360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
I'm not sure why, but within the scope of the onclick execution, checked is a local variable that contains the checkbox's clicked property.
There are several ways you can resolve this:
Rename the function so it doesn't conflict with this variable.
Call it as window.checked().
Assign the handler by assigning to the onclick property or calling addEventListener rather than putting it in the HTML.
I've chosen the last method.
Also, IDs should be unique, you can't reuse the IDs check and tsks for every task. You can refer to the box that was clicked on with this in the function, and the containing p element with this.parentElement.
A p element doesn't have a value property, use textContent to get the name of the task.
var name = prompt("Please Enter Your Name :)");
document.write('<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function () {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function () {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function () {
var newEl = document.createElement("p");
newEl.innerHTML = "<input type = 'checkbox'>" + task.value + ' ' + date.value;
newEl.querySelector("input").addEventListener("click", checked);
document.getElementById('task2').appendChild(newEl);
}
function checked() {
if (this.checked) {
var tsks = this.parentElement;
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.innerText + "Good Job!");
}
}
body {
background-image: url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color: white;
width: 700px;
height: 400px;
position: absolute;
left: 325px;
top: 150px;
}
#greet {
position: absolute;
left: 445px;
top: 150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color: blue;
font-weight: bold;
position: absolute;
left: 625px;
top: 230px;
}
#b {
background-image: linear-gradient(#2980B9, #6DD5FA, #fff);
color: black;
border-color: white;
text-weight: bold;
width: 70px;
height: 50px;
position: absolute;
left: 625px;
top: 260px;
}
.To-Do {
width: 100%;
height: 100%;
position: absolute;
top: 0;
display: flex;
justify-content: center;
align-items: center;
display: none;
z-index: 1;
}
.modal-content {
width: 500px;
height: 300px;
border-radius: 10px;
position: relative;
background-color: purple;
}
.close {
position: absolute;
top: 0;
right: 14px;
font-size: 32px;
transform: rotate(45deg);
cursor: pointer;
}
#aat {
background-color: white;
font-weight: bold;
}
h2 {
position: absolute;
left: 590px;
top: 305px;
border-bottom: 5px solid blue;
}
p {
font-weight: bold;
position: relative;
left: 590px;
top: 360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
Hey it worked by changing if(check.onclick == true) to if(check.checked == true) and also function name from checked to chec, because checked is a property in java script . So this keyword cannot be used as function name.
var name = prompt("Please Enter Your Name :)");
document.write( '<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function() {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function() {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function() {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks" );
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'chec()'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function chec() {
if(check.checked == true) {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
}
body {
background-image:url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color:white;
width:700px;
height:400px;
position:absolute;
left:325px;
top:150px;
}
#greet {
position:absolute;
left:445px;
top:150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color:blue;
font-weight:bold;
position:absolute;
left:625px;
top:230px;
}
#b {
background-image:linear-gradient(#2980B9, #6DD5FA, #fff);
color:black;
border-color:white;
text-weight:bold;
width:70px;
height:50px;
position:absolute;
left:625px;
top:260px;
}
.To-Do {
width:100%;
height:100%;
position:absolute;
top:0;
display:flex;
justify-content:center;
align-items:center;
display:none;
z-index:1;
}
.modal-content {
width:500px;
height:300px;
border-radius:10px;
position:relative;
background-color:purple;
}
.close {
position:absolute;
top:0;
right:14px;
font-size:32px;
transform:rotate(45deg);
cursor:pointer;
}
#aat {
background-color:white;
font-weight:bold;
}
h2 {
position:absolute;
left:590px;
top:305px;
border-bottom:5px solid blue;
}
p {
font-weight:bold;
position:relative;
left:590px;
top:360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
I got it to work by changing checked() to window.checked() and removing the if statement in side the checked function
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'window.checked()'>" + task.value + ' ' + date.value;
function checked() {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
Two points:
You have used function "checked" on the checkbox. It is the name of
property, so choose any other name
To change only selected
element - pass it to event handler.
Working example: https://jsfiddle.net/zordaxy/L0sbp8mt/27/
document.getElementById("b").onclick = function() {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function() {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("s").onclick = function() {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks" );
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'checked2(this);'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function checked2(item) {
console.log(item);
item.parentElement.style.textDecoration = "line-through";
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<p align = "center" id = "aat" onclick='checked()'>ADD A TASK</p>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
I have this code below that is able to transfer the array value to another array when i click on it. For Example, when i click on lime it will move into my Green Array The problem is after i JSON.stringify my Green Array it doesn't show the updated value.
So this is the before i add in a value my green array has 5 values.
And this is after I add in a value to my green array as you can see after I move the value in my array count increases but I don't know why when i stringify the array, it doesn't have the value I added in already I want to stringify it because I want to send the updated data to a server. Is there any reason why this is happening ?
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
var randomFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = randomFruits;
function redraw() {
var combineString = '';
$.each(red[key], function(index) {
combineString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.combineclass').html(combineString);
$.each(green[key2], function(index) {
combineString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.combineclass').html(combineString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data) {
if (fruits[i].type === "1") {
red[key].push(data);
} else {
green[key2].push(data);
}
}
}
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data2) {
if (fruits[i].type === "1") {
k2 = Object.keys(red).find(k => red[k].indexOf(data2) >= 0);
index2 = red[k2].indexOf(data2);
red[k2].splice(index2, 1);
} else {
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0);
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
}
}
}
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').prepend('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
var testing = JSON.stringify(green);
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.randompill:after{
content: "\002B";
float: left;
width:16px;
}
.new-green-fruit:after{
content: "\292B";
float: left;
width:16px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Total Fruits</h3>
<div id="combineid" class="combineclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Random Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
It is working fine as expected. Look into the code base properly may be you are missing something.
var greenFruits = ["Watermelon", "Durian", "Avacado", "Lime", "Honeydew"];
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));
greenFruits.push("Guava");
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));