I can't get the JavaScript toggle to work - javascript

What I want to do is when I click the task it will have a line through the text means that I'm done with the task. but the add event listener function for this is not working, I'm working with the javascript toggle and that's all I can think of right now to achieve this functionality.
Is there another way to do this? I searched on the internet and it seems complicated when I'm trying to figure it out.
const addBtn = document.querySelector("#push");
const taskInput = document.querySelector("#taskInput");
const taskOutput = document.querySelector("#tasks");
addBtn.addEventListener("click", function() {
let newTasks = taskInput.value;
if (newTasks.length == 0) {
alert("Please enter a task");
} else {
taskOutput.innerHTML += `<div class="task">
<span id="taskname">${newTasks} </span>
<button class="delete" id="deleteButton"><i class="fa-solid fa-trash"></i> </button>
</div>
`;
//delete
let deleteBtn = document.querySelector("#deleteButton");
deleteBtn.addEventListener("click", function() {
this.parentNode.remove();
});
//line through
let theTask = document.querySelectorAll(".task");
theTask.addEventListener("click", function() {
this.classList.toggle("completed");
});
}
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background: linear-gradient( 90deg, rgba(241, 206, 221, 1) 0%, rgba(124, 184, 254, 1) 100%);
display: flex;
justify-content: center;
align-items: center;
font-family: 'Kumbh Sans', sans-serif;
}
.container {
border: 2px solid white;
width: 50%;
min-width: 450px;
margin: auto;
padding: 30px 40px;
}
#new-task {
position: relative;
background-color: white;
padding: 30px 20px;
border-radius: 1em;
}
#new-task input {
width: 70%;
height: 45px;
font-family: 'Manrope', sans-seif;
font-size: 1.2em;
border: 2px solid #d1d3d4;
padding: 12px;
color: #111111;
font-weight: 500;
position: relative;
border-radius: 5px;
}
#new-task input:focus {
outline: none;
border-color: violet;
}
#new-task button {
font-family: 'Manrope', sans-seif;
position: relative;
float: right;
width: 25%;
height: 45px;
border-radius: 5px;
font-weight: bold;
font-size: 16px;
border: none;
background-color: violet;
color: white;
cursor: pointer;
}
#tasks {
background-color: white;
padding: 30px 20px;
margin-top: 50px;
border-radius: 10px;
width: 100%;
}
.task {
background-color: white;
height: 50px;
padding: 5px 10px;
margin-top: 10px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 2px solid violet;
cursor: pointer;
}
.task span {
font-size: 18px;
font-weight: 400;
}
.task button {
background-color: violet;
color: white;
height: 100%;
width: 40px;
border: none;
border-radius: 5px;
outline: none;
cursor: pointer;
}
.task button:hover {
background-color: red;
}
.completed {
text-decoration: line-through;
}
<body>
<div class="container">
<div id="new-task">
<input type="text" name="" id="taskInput" placeholder="Task to be done" />
<button id="push">ADD</button>
</div>
<div id="tasks"></div>
</div>
<script src="/script.js"></script>
</body>

querySelectorAll will return the list of nodes matching the selector tasks. So you have to iterate through each of those nodes and add your listener. See the below code snippet
let theTasks = document.querySelectorAll(".task");
theTasks.forEach((task) => {
task.addEventListener("click", function() {
this.classList.toggle("completed");
});
});

theTask is a list of nodes. Trying to attach event listener on this list is causing issues.
Also, you will be inserting lots of buttons with same id deleteButton and spans with same id taskname which is incorrect and can cause undefined behavior.
For theTask fix, you may want to do something like:
let theTasks = [...document.querySelectorAll(".task")];
theTasks.forEach(task => {
task.addEventListener("click", function() {
this.classList.toggle("completed");
})
});

Using innerHTML to create manipulate the DOM for an application like a todo list is probably not a good idea. The answers to Advantages of createElement over innerHTML? give good explanations why.
It is worth noting that in the innerHTML code, the span and the button are created with an id and so all of these elements will have the same id. It is also probably not a good idea to have duplicate ids on one page. Why are duplicate ID values not allowed in HTML? explains why.
Also, adding event listeners to every new task is also probably not a good idea. What is DOM Event delegation? gives a good explanation why.
Finally, the Difference between HTMLCollection, NodeLists, and arrays of objects and Document.querySelectorAll() explain how to get lists of elements that can be manipulated.
So, I have rewritten the task creation code in the addBtn.addEventListener to show one way how this could be done with document.createElement().
And I have created a separate event listener on the Tasks container div, which handles both task deletion and task completion.
I also added the following CSS so that clicking on a trash can icon is handled by the parent button. Without this CSS, clicking on an icon would not delete the task.
div#tasks i {
pointer-events: none;
}
To make the todo list more visible in the code snippet below, I reduced the heights, margins, and paddings of some of the elements in the CSS.
I also added a link to the font awesome icon library.
const addBtn = document.querySelector("#push");
const taskInput = document.querySelector("#taskInput");
const taskOutput = document.querySelector("#tasks");
taskOutput.addEventListener("click", function(event) {
if (event.target && event.target.nodeName === "SPAN") {
event.target.classList.toggle("completed");
}
if (event.target && event.target.nodeName === "BUTTON") {
event.target.parentNode.remove();
}
});
addBtn.addEventListener("click", function() {
let newTasks = taskInput.value;
if (newTasks.length == 0) {
alert("Please enter a task");
} else {
// Create a task DIV
const newTaskElement = document.createElement("div");
newTaskElement.classList.add("task");
// Create a SPAN with the task name
const newTaskNameElement = document.createElement("span");
const taskTextnode = document.createTextNode(newTasks);
newTaskNameElement.appendChild(taskTextnode);
// Create a BUTTON with a TRASH CAN ICON
const newTaskDeleteButton = document.createElement("button");
const deleteImageElement = document.createElement("i");
deleteImageElement.classList.add("fa-solid", "fa-trash");
newTaskDeleteButton.appendChild(deleteImageElement);
// Append the SPAN and the BUTTON to the task DIV
newTaskElement.appendChild(newTaskNameElement);
newTaskElement.appendChild(newTaskDeleteButton);
// Append the task DIV to the TASK LIST DIV
taskOutput.appendChild(newTaskElement);
}
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background: linear-gradient( 90deg, rgba(241, 206, 221, 1) 0%, rgba(124, 184, 254, 1) 100%);
font-family: 'Kumbh Sans', sans-serif;
}
/* ADDED TO MAKE SURE THAT THE TRASH ICON DOES NOT PROCESS CLICKS */
div#tasks i {
pointer-events: none;
}
.container {
border: 2px solid white;
width: 50%;
min-width: 450px;
margin: auto;
padding: 3px 4px;
}
#new-task {
position: relative;
background-color: white;
padding: 6px 4px;
border-radius: 1em;
}
#new-task input {
width: 70%;
height: 45px;
font-family: 'Manrope', sans-seif;
font-size: 1.2em;
border: 2px solid #d1d3d4;
padding: 12px;
color: #111111;
font-weight: 500;
position: relative;
border-radius: 5px;
}
#new-task input:focus {
outline: none;
border-color: violet;
}
#new-task button {
font-family: 'Manrope', sans-seif;
position: relative;
float: right;
width: 25%;
height: 45px;
border-radius: 5px;
font-weight: bold;
font-size: 16px;
border: none;
background-color: violet;
color: white;
cursor: pointer;
}
#tasks {
background-color: white;
padding: 6px 4px;
margin-top: 5px;
border-radius: 10px;
width: 100%;
min-height: 50px;
}
.task {
background-color: white;
height: 50px;
padding: 5px 10px;
margin-top: 10px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 2px solid violet;
cursor: pointer;
}
.task span {
font-size: 18px;
font-weight: 400;
}
.task button {
background-color: violet;
color: white;
height: 100%;
width: 40px;
border: none;
border-radius: 5px;
outline: none;
cursor: pointer;
}
.task button:hover {
background-color: red;
}
.completed {
text-decoration: line-through;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" rel="stylesheet" />
<div class="container">
<div id="new-task">
<input type="text" name="" id="taskInput" placeholder="Task to be done" />
<button id="push">ADD</button>
</div>
<div id="tasks"></div>
</div>

Related

Why does my eventlistener for input search doesnt work?

I am working on an application to search for cities. It returns a card with the flag, capital, population and region; however, it works only until I try to add an eventListener to the input search, after which, it does nothing.
Am I calling the search incorrectly? should I maybe do a search function?
P. S: I started coding ~6 months ago and sorry if it is a not well-constructed code.
const APICALL = 'https://restcountries.eu/rest/v2/';
const form = document.querySelector('.recherche')
const input = document.querySelector('.inpRecherche');
const searchBtn = document.querySelector('.searchBtn');
const affichage = document.querySelector('.affichage');
let cities = [];
//API call
async function dataApi(cities) {
const call = await fetch(APICALL);
const data = await call.json();
cities = data;
//console.log(cities);
createCard(cities);
}
dataApi(cities)
function createCard(cities) {
for (let i = 0; i < cities.length; i++) {
const cardHTML = `
<div class="carte">
<img src="${[cities[i].flag]}" alt="flag" class="avatar">
<h2>${[cities[i].name]}</h2>
<ul class="cont-infos">
<li class="capital">Capital : ${[cities[i].capital]}</li>
<li class="population">Population: ${[cities[i].population]}</li>
<li class="subregion">Region : ${[cities[i].subregion]}</li>
</ul>
</div>
`;
affichage.innerHTML = cardHTML;
}
}
searchBtn.addEventListener('click', dataApi);
form.addEventListener('submit', (e) => {
e.preventDefault()
if (e.value > 0) {
//console.log('hello');
dataApi([cities[i]]);
input.value = "";
}
})
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
height: 100vh;
background-image: url("Background.jpg");
font-family: Arial, Helvetica, sans-serif;
background-size: cover;
}
h1 {
font-size: 35px;
text-align: center;
margin: 30px;
}
.inpRecherche {
display: block;
width: 250px;
padding: 3px;
font-size: 12px;
}
form,
.affichage {
display: flex;
width: 100%;
height: auto;
align-items: center;
justify-content: center;
border-radius: 2px;
}
.affichage {
position: absolute;
justify-content: center;
border: 2px solid whitesmoke;
border-radius: 5px;
width: 300px;
height: 300px;
margin: 20px 480px;
}
.searchBtn {
height: 25px;
padding: 2px 5px;
background-color: #2896F6;
box-shadow: none;
cursor: pointer;
color: whitesmoke;
font-weight: bold;
border-radius: 3px solid white;
}
.searchBtn:hover {
background-color: #167CD4;
}
/* a partir d'ici c'est à créer
*/
.card {
width: 500px;
height: auto;
position: relative;
margin-top: 200px;
padding-bottom: 20px;
border-radius: 5px;
background-color: beige;
}
.avatar {
height: 150px;
width: 150px;
margin-top: 80px;
border-radius: 50%;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #000;
border: 1px solid black;
}
h2 {
margin-top: 100px;
text-align: center;
font-size: 25px;
}
.cont-infos {
border-top: 1px dashed black;
margin-top: 20px;
list-style-type: none;
}
li {
padding: 10px 20px;
text-align: justify;
font-size: 22px;
}
li:nth-child(1) {
margin-top: 15px;
}
<h1>City finder 🌍🏃</h1>
<form class="recherche">
<input type="text" class="inpRecherche" placeholder="Rechercher une ville">
<button class="searchBtn">Chercher</button>
</form>
<div class="affichage">
</div>
The first thing that comes to my attention is the argument you're passing to the dataApi function. When you pass it to the event listener, the argument it receives is an event object (you're just naming it "cities"), and then you're trying to overwrite it with data from the API call instead of updating the global cities array.
Hi Lizeth and welcome to StackOverflow.
I'm not completely sure of what you are trying to do, but right now, your function createCard is not looping over all the cities you receive from the API, but writing over and over the content of cardHTML. To display all the cities, you can add a +in front of the = and
function createCard(cities) {
for (let i = 0; i < cities.length; i++) {
const cardHTML = `
<div class="carte">
<img src="${[cities[i].flag]}" alt="flag" class="avatar">
<h2>${[cities[i].name]}</h2>
<ul class="cont-infos">
<li class="capital">Capital : ${[cities[i].capital]}</li>
<li class="population">Population: ${[cities[i].population]}</li>
<li class="subregion">Region : ${[cities[i].subregion]}</li>
</ul>
</div>
`;
affichage.innerHTML += cardHTML;
}
}
And change your css classes to
.affichage {
justify-content: center;
border: 2px solid whitesmoke;
border-radius: 5px;
width: 90vw;
height: auto;
margin: 20px auto 0 auto;
display: flex;
flex-flow: row wrap;
}
.avatar {
height: 150px;
width: 150px;
margin: 10px auto;
border-radius: 50%;
position: initial;
background-color: #000;
border: 1px solid black;
margin: 10px auto;
}
But, be warned, building html this way can be very dangerous, see XSS attacks.
And to search for a city using the input, Yes, you need to build a search function yourself, and display the result. Regex could be a way to do it

JavaScript addEventListener "click" for button that moves while clicking

I have a button styled to move when clicking. If the button is not in position with the mouse cursor when releasing, the click function is not triggered. How can I still make the click function trigger as expected?
Here is a fiddle with the HTML, CSS and JavaScript. Notice if you hold a click and release in a place where the button does not exist under your mouse pointer, it will not trigger the function.
https://jsfiddle.net/du1eL8gc/1/
Just a note: I know that it makes sense this does not trigger because the button is actually moving out of place, I just want to have it work as a user would expect.
HTML:
<div class="buttons-dialog" style="position:absolute; bottom:20px; left:33%">
<a class="button" id="saveButton">Save</a>
</div>
CSS:
#import url('https://fonts.googleapis.com/css?family=IBM+Plex+Mono');
:root {
--blueColor: #0028aa;
--darkBlueColor: #022693;
--errorColor: rgb(255, 130, 0);
--grayColor: #bcbdaa;
--darkgrayColor: #525252;
--cyanColor: #59ffff;
--yellowColor: #fffa51;
--emeraldColor: #184343;
--lightEmeraldColor: #38a6a6;
--redColor: #9c0b07;
--badTextColor: #fe6666;
--highlightTextColor: #ffffff;
--fontName: 'IBM Plex Mono', monospaced;
font-family: var(--fontName);
font-size: 16px;
}
body {
background: var(--blueColor);
}
.button-panel {
margin-bottom: 1.5em;
}
.button {
background: var(--darkgrayColor);
border: 0;
font-family: var(--fontName);
font-size: 1rem;
color: var(--grayColor);
outline: 0;
padding: 2px;
margin-right: 1em;
box-shadow: 10px 8px 0 black;
text-decoration: none;
}
.buttonNoShadow {
background: var(--darkgrayColor);
border: 0;
font-family: var(--fontName);
font-size: 1rem;
color: var(--grayColor);
outline: 0;
padding: 2px;
margin-right: 1em;
text-decoration: none;
}
.button:active {
color: var(--highlightColor);
position: relative;
left: 10px;
top: 8px;
box-shadow: none;
}
.button::before {
content: "▯ ";
color: var(--highlightColor);
}
.button::after {
content: " ▯";
color: var(--highlightColor);
}
JavaScript:
document.getElementById("saveButton").addEventListener("click", function () {
console.log('clicked')
});
You can use your JavaScript with the "mouseup" event and have it work by wrapping your button content and moving that content instead of your button.
Working example: https://jsfiddle.net/8a5upveg/3/
For instance you can wrap the text in a <span>:
<a class="button" id="saveButton"><span>Save</span></a>
Then change your CSS to target the <span>:
.button {
// Seems necessary to catch top pixel of button click
padding: 1px;
}
.button span {
background: var(--darkgrayColor);
border: 0;
font-family: var(--fontName);
font-size: 1rem;
color: var(--grayColor);
outline: 0;
padding: 2px;
margin-right: 1em;
box-shadow: 10px 8px 0 black;
text-decoration: none;
}
.buttonNoShadow span {
background: var(--darkgrayColor);
border: 0;
font-family: var(--fontName);
font-size: 1rem;
color: var(--grayColor);
outline: 0;
padding: 2px;
margin-right: 1em;
text-decoration: none;
}
.button:active span {
color: var(--highlightColor);
position: relative;
left: 10px;
top: 8px;
box-shadow: none;
}
.button span::before {
content: "▯ ";
color: var(--highlightColor);
}
.button span::after {
content: " ▯";
color: var(--highlightColor);
}
Instead of .addEventListener("click", function() {});, you can use .addEventListener("mousedown", function() {});, which works exactly as you wanted.
Then the function will be called even if the mouse button is released outside of the moving button.

Calling Child click event when parent is clicked

Basically I am having a third party plugin that is adding a button on the click of this button a specific function is done.
Now I am wrapping this button into a div. Now I want that when I click on this wrapper div then it should click the button that is inside it.
// find elements
var banner = $("#banner-message")
var button = $("button")
banner.click(function() {
console.log('Parent is calling child');
button.trigger('click');
// What shall I place here to stop parent calling itself
})
// This is 3rd party service that is handling this.
button.on("click", function() {
console.log('I am called here');
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Change color</button>
</div>
Demo : https://jsfiddle.net/8a33n7qg/
Problem : On div click => button click is done => button click is again propagated to parent => then again button click and so on.
So I want to stop this after first time, I can't change the third party plugin and I am avoiding global solutions. Is there any easy solution ?
Note : I CAN'T CHANGE THE BUTTON CODE, SINCE IT COMING FROM THIRD PARTY PLUGIN
Thank You for your time
Your need to place a call to stopPropagation() in the event raised from the child button, not the parent div as your comments suggest:
var $banner = $("#banner-message");
var $button = $("button");
$banner.click(function(){
console.log('Parent is calling child');
$button.trigger('click');
})
$button.on("click", function(e) {
e.stopPropagation();
console.log('I am called here');
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Change color</button>
</div>
I can't change the third party plugin, I have tried to show a demo with small code, the button click is handled in third part plugin.
In this case you can use the target property of the click event on the div to check if the button was the triggering element, and do nothing if so:
var $banner = $("#banner-message");
var $button = $("button");
$banner.click(function(e) {
if ($(e.target).is('button'))
return false;
console.log('Parent is calling child');
$button.trigger('click');
})
$button.on("click", function() {
console.log('I am called here');
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Change color</button>
</div>
Just use event.stopPropagation() in button on handler to stop propagating the event.

To Do List Delete Button within HTML <li> element

I am trying to get a delete button working on my To Do List project. I have tried a lot of different things but I am not having any luck. I believe the issue stems from the fact that I am trying to reference a button in an HTML li tag that is created by Javascript/jQuery when a user enters a new task in the To Do List. I probably am messing up the syntax relation between the two. Any help would be greatly appreciated. Thanks ahead of time.
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Project 4 - To Do List</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="page">
<h1 id="header"></h1>
<h2>To Do List <span id="counter"></span></h2>
<h3>"If you can dream it, you can do it" - Walt Disney</h3>
<div id="newItemButton"><button href="#" id="showForm">New Entry</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Enter goal" />
<input type="submit" id="add" value="Submit"/>
</form>
<ul>
<!--<li id="one">Exercise</li>
<li id="two">Study</li>
<li id="three">Practice a New Language</li>
<li id="four">Work on Personal Project</li>-->
</ul>
</div>
<div class="about">
<a id="link" href="x">About</a>
</div>
<script src="jquery-1.11.0.js"></script>
<script src="javascript_jquery.js"></script>
</body>
<footer>
<div id="footer">To do List Icons made by <a id="link" href="http://www.freepik.com" title="Freepik">Freepik</a> from <a id="link" href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a id="link" href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>
</div>
<div id="footer">Trash Icons made by <a id="link" href="https://www.flaticon.com/authors/dave-gandy" title="Dave Gandy">Dave Gandy</a> from <a id="link" href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a id="link" href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div>
</footer>
</html>
Here is the Javascript/jQuery. The focus of my issue is on the Delete function at the bottom and probably the .append part under "Check as Complete."
/*eslint-env jquery*/
/* eslint-env browser */
$(document).ready(function() {
// SETUP
var $list, $newItemForm, $newItemButton;
var item = ''; // item is an empty string
$list = $('ul'); // Cache the unordered list
$newItemForm = $('#newItemForm'); // Cache form to add new items
$newItemButton = $('#newItemButton'); // Cache button to show form
// ITEM COUNTER
function updateCount() { // Create function to update counter
var items = $('li[class!=complete]').length; // Number of items in list
$('#counter').text(items); // Added into counter circle
}
updateCount(); // Call the function
// SETUP FORM FOR NEW ITEMS
$newItemButton.show(); // Show the button
$newItemForm.hide(); // Hide the form
$('#showForm').on('click', function() { // When click on add item button
$newItemButton.hide(); // Hide the button
$newItemForm.show(); // Show the form
});
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function(e) { // When a new item is submitted
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
$list.append('<li>' + text + '</li>'); // Add item to end of the list
$('input:text').val(''); // Empty the text input
updateCount(); // Update the count
});
//Check as Complete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete !== true) {
item = $this.text(); // Get the text from the list item
$this.remove(); // Remove the list item
$list // Add back to end of list as complete
.append('<li class=\"complete\">' + item + '<button type="button" class="trashbutton" src="/images/icon-trash.png" alt="Trash Icon"></button>' + '</li>')
.hide().fadeIn(300); // Hide it so it can be faded in
complete = true;
}
updateCount();
});
/*//Check as Incomplete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
item = $this.text();
$this.remove();
$list
.append('<li>' + item + '</li>')
.hide().fadeIn(300);
}
updateCount();
});*/
// Delete
$list.on('click', 'li', function() {
var $this = $(this);
var readyToDelete = $this.hasClass('trashbutton');
if(readyToDelete === true) {
$this.animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$this.remove();
});
}
updateCount;
});
});
Here is the CSS just in case.
#import url(http://fonts.googleapis.com/css?family=Oswald);
body {
background-color: whitesmoke;
font-family: 'Oswald', 'Futura', sans-serif;
margin: 0;
padding: 0;
}
#page {
background-color: black;
margin: 0 auto 0 auto;
position: relative;
text-align: center;
}
/* Responsive page rules at bottom of style sheet */
h1 {
background-image: url('/images/icon.png');
background-repeat: no-repeat;
background-position: center center;
text-align: center;
text-indent: -1000%;
height: 75px;
line-height: 75px;
width: 117px;
margin: auto auto auto auto;
padding: 30px 10px 20px 10px;
}
h2 {
color: #fff;
font-size: 24px;
font-weight: normal;
text-align: center;
text-transform: uppercase;
letter-spacing: .3em;
display: inline-block;
margin: 0 0 23px 0;
}
h2 span {
background-color: #fff;
color: green;
font-size: 12px;
text-align: center;
letter-spacing: 0;
display: inline-block;
position: relative;
border-radius: 50%;
top: -5px;
height: 22px;
width: 26px;
padding: 4px 0 0 0;
}
h3 {
color: white;
}
ul {
border:none;
padding: 0;
margin: 0;
}
li {
background-color: yellowgreen;
color: black;
border-top: 1px solid grey;
border-bottom: 1px solid grey;
font-size: 24px;
letter-spacing: .05em;
list-style-type: none;
text-shadow: 1px 1px 1px grey;
text-align: left;
height: 50px;
padding-left: 1em;
padding-top: 10px;
padding-right: 1em;
}
/* unvisited link */
#link:link {
color: yellowgreen;
}
/* visited link */
#link:visited {
color: green;
}
/* mouse over link */
#link:hover {
color: darkseagreen;
}
/* selected link */
#link:active {
color: forestgreen;
}
.about {
text-align: center;
}
#footer {
background:none;
color: black;
text-align: center;
}
.complete {
background-color: #999;
color: white;
border-top: 1px solid #666;
border-bottom: 1px solid #b0b0b0;
text-shadow: 2px 2px 1px #333;
}
.trashbutton {
background-image: url('/images/icon-trash.png');
background-position: center;
background-repeat: no-repeat;
background-size: 12px 12px;
margin: auto !important;
position: relative;
top: 35%;
transform: translateY(-50%);
}
/* FORM STYLES */
form {
padding: 0 20px 20px 20px;
}
input[type='text'], input[type='password'], textarea {
background-color: whitesmoke;
color: black;
font-size: 24px;
width: 96%;
padding: 4px 6px;
border: 1px solid #999;
border-radius: 8px;}
input[type='submit'], a.add, button, a.show {
background-color: yellowgreen;
color: black;
border-radius: 8px;
border: none;
padding: 8px 10px;
margin-top: 10px;
font-family: 'Oswald', 'Futura', sans-serif;
font-size: 18px;
text-shadow: 1px 1px 1px grey;
text-decoration: none;
text-transform: uppercase;}
input[type='submit'], button {
float: right;
}
input[type='submit']:hover {
background-color: green;
color: #fff;
cursor: pointer;
}
/* form example */
#newItemButton {
padding: 10px 20px 75px 20px;
display: none;
}
#newItemForm {
padding-top: 20px;
}
#itemDescription {
width: 325px;
}
#newItemForm input[type='submit'] {
margin-top: 0;
text-align: center;
}
/* Attributes example */
#group {
margin: 10px;
border: 2px solid #fff;
}
/* Small screen:mobile */
#media only screen and (max-width: 500px) {
body {
background-color: #403c3b;
}
#page {
max-width: 480px;
}
}
#media only screen and (min-width: 501px) and (max-width: 767px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media only screen and (min-width: 768px) and (max-width: 959px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
/* Larger screens act like a demo for the app */
#media only screen and (min-width: 960px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
h1{
background-image: url('/images/icon.png');
background-size: 100px 100px;
}
}
Some screenshots of what works so far. You can see the tasks as incomplete in green, completed in grey, and the trash button shows up when the task is grey.
When app first loads
One incomplete task and one complete task. Notice trash button that does not work.
NOTE: I should mention that, while heavily altered, the HTML and JS code is derived from an example from Jon Duckett's Javascript and jQuery book. This is my first time ever working with jQuery and the purpose of this assignment is to learn the basics.
Here is how you can get it working:
Change $list.on('click', 'li', function() { to $list.on('click', 'li > button', function() { (your list items doesn't have 'trashbutton' class).
Update code you use to delete element since after clicking on a button you have to delete parent element (li), not the button itself.
Take a look at this in action:
$(document).ready(function() {
// SETUP
var $list, $newItemForm, $newItemButton;
var item = ''; // item is an empty string
$list = $('ul'); // Cache the unordered list
$newItemForm = $('#newItemForm'); // Cache form to add new items
$newItemButton = $('#newItemButton'); // Cache button to show form
// ITEM COUNTER
function updateCount() { // Create function to update counter
var items = $('li[class!=complete]').length; // Number of items in list
$('#counter').text(items); // Added into counter circle
}
updateCount(); // Call the function
// SETUP FORM FOR NEW ITEMS
$newItemButton.show(); // Show the button
$newItemForm.hide(); // Hide the form
$('#showForm').on('click', function() { // When click on add item button
$newItemButton.hide(); // Hide the button
$newItemForm.show(); // Show the form
});
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function(e) { // When a new item is submitted
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
$list.append('<li>' + text + '</li>'); // Add item to end of the list
$('input:text').val(''); // Empty the text input
updateCount(); // Update the count
});
//Check as Complete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete !== true) {
item = $this.text(); // Get the text from the list item
$this.remove(); // Remove the list item
$list // Add back to end of list as complete
.append('<li class=\"complete\">' + item + '<button type="button" class="trashbutton" src="/images/icon-trash.png" alt="Trash Icon"></button>' + '</li>')
.hide().fadeIn(300); // Hide it so it can be faded in
complete = true;
}
updateCount();
});
/*//Check as Incomplete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
item = $this.text();
$this.remove();
$list
.append('<li>' + item + '</li>')
.hide().fadeIn(300);
}
updateCount();
});*/
// Delete
$list.on('click', 'li > button', function() {
var $this = $(this);
var readyToDelete = $this.hasClass('trashbutton');
if(readyToDelete === true) {
$this.parent().animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$(this).remove();
});
}
updateCount;
});
});
#import url(http://fonts.googleapis.com/css?family=Oswald);
body {
background-color: whitesmoke;
font-family: 'Oswald', 'Futura', sans-serif;
margin: 0;
padding: 0;
}
#page {
background-color: black;
margin: 0 auto 0 auto;
position: relative;
text-align: center;
}
/* Responsive page rules at bottom of style sheet */
h1 {
background-image: url('/images/icon.png');
background-repeat: no-repeat;
background-position: center center;
text-align: center;
text-indent: -1000%;
height: 75px;
line-height: 75px;
width: 117px;
margin: auto auto auto auto;
padding: 30px 10px 20px 10px;
}
h2 {
color: #fff;
font-size: 24px;
font-weight: normal;
text-align: center;
text-transform: uppercase;
letter-spacing: .3em;
display: inline-block;
margin: 0 0 23px 0;
}
h2 span {
background-color: #fff;
color: green;
font-size: 12px;
text-align: center;
letter-spacing: 0;
display: inline-block;
position: relative;
border-radius: 50%;
top: -5px;
height: 22px;
width: 26px;
padding: 4px 0 0 0;
}
h3 {
color: white;
}
ul {
border:none;
padding: 0;
margin: 0;
}
li {
background-color: yellowgreen;
color: black;
border-top: 1px solid grey;
border-bottom: 1px solid grey;
font-size: 24px;
letter-spacing: .05em;
list-style-type: none;
text-shadow: 1px 1px 1px grey;
text-align: left;
height: 50px;
padding-left: 1em;
padding-top: 10px;
padding-right: 1em;
}
/* unvisited link */
#link:link {
color: yellowgreen;
}
/* visited link */
#link:visited {
color: green;
}
/* mouse over link */
#link:hover {
color: darkseagreen;
}
/* selected link */
#link:active {
color: forestgreen;
}
.about {
text-align: center;
}
#footer {
background:none;
color: black;
text-align: center;
}
.complete {
background-color: #999;
color: white;
border-top: 1px solid #666;
border-bottom: 1px solid #b0b0b0;
text-shadow: 2px 2px 1px #333;
}
.trashbutton {
background-image: url('/images/icon-trash.png');
background-position: center;
background-repeat: no-repeat;
background-size: 12px 12px;
margin: auto !important;
position: relative;
top: 35%;
transform: translateY(-50%);
}
/* FORM STYLES */
form {
padding: 0 20px 20px 20px;
}
input[type='text'], input[type='password'], textarea {
background-color: whitesmoke;
color: black;
font-size: 24px;
width: 96%;
padding: 4px 6px;
border: 1px solid #999;
border-radius: 8px;}
input[type='submit'], a.add, button, a.show {
background-color: yellowgreen;
color: black;
border-radius: 8px;
border: none;
padding: 8px 10px;
margin-top: 10px;
font-family: 'Oswald', 'Futura', sans-serif;
font-size: 18px;
text-shadow: 1px 1px 1px grey;
text-decoration: none;
text-transform: uppercase;}
input[type='submit'], button {
float: right;
}
input[type='submit']:hover {
background-color: green;
color: #fff;
cursor: pointer;
}
/* form example */
#newItemButton {
padding: 10px 20px 75px 20px;
display: none;
}
#newItemForm {
padding-top: 20px;
}
#itemDescription {
width: 325px;
}
#newItemForm input[type='submit'] {
margin-top: 0;
text-align: center;
}
/* Attributes example */
#group {
margin: 10px;
border: 2px solid #fff;
}
/* Small screen:mobile */
#media only screen and (max-width: 500px) {
body {
background-color: #403c3b;
}
#page {
max-width: 480px;
}
}
#media only screen and (min-width: 501px) and (max-width: 767px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media only screen and (min-width: 768px) and (max-width: 959px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
/* Larger screens act like a demo for the app */
#media only screen and (min-width: 960px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
h1{
background-image: url('/images/icon.png');
background-size: 100px 100px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">
<h1 id="header"></h1>
<h2>To Do List <span id="counter"></span></h2>
<h3>"If you can dream it, you can do it" - Walt Disney</h3>
<div id="newItemButton"><button href="#" id="showForm">New Entry</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Enter goal" />
<input type="submit" id="add" value="Submit"/>
</form>
<ul>
<!--<li id="one">Exercise</li>
<li id="two">Study</li>
<li id="three">Practice a New Language</li>
<li id="four">Work on Personal Project</li>-->
</ul>
</div>
<div class="about">
<a id="link" href="x">About</a>
</div>
<script src="jquery-1.11.0.js"></script>
<script src="javascript_jquery.js"></script>
It would be easier for you to accomplish your task by giving the trashbutton class a click event to remove its parent li from the list. This can be accomplished with the following code.
// Delete
$('.trashbutton').click(function (e) {
e.preventDefault();
$(this).parent().animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$(this).parent().remove();
});
}
updateCount();
})

Issue with jQuery chat form

Thank you for the help in advance.
This project is a signup form that will use a chat system to collect the user's profile details during their onboarding process. This is my first jQuery project, so I am struggling to spot my mistakes.
My jQuery should append the value in the textarea to the #message-feed div and apply the CSS classes of .message, .bubble and .user to the new element it creates.
However, when I type into the text area and click submit, it flashes the value I have just typed with no styling in the message feed, but it instantly disappears.
The reason for this CSS structure is the interchangeability between the .bot and .user classes depending on whether it is a question presented to the user by the website, or a user's response to a question.
Here is a link for a JSFiddle but it loads very differently than on my local machine (JSFiddle shows errors.
HTML
<div id="container">
<div id="message-feed">
<h1>Let's get to know you a little bit more…</h1>
</div>
<form method="POST">
<div id="text-response">
<textarea id="text-response" placeholder="Type in here…"></textarea>
</div>
<input type="submit" class="submit-response">
</form>
</div>
CSS
#container {
width: 320px;
height: 480px;
background-color: #fff;
position:absolute;
left:50%;
top:50%;
margin:-240px 0 0 -160px;
}
#message-feed {
width: 100%;
height: 100%;
margin: auto;
overflow-y: scroll;
}
.message {
padding: 0px 15px 15px 15px;
width: 90%;
}
.message:after {
content:"";
display: block;
clear: both;
}
.bubble {
border: 0.5px solid #005393;
max-width: 80%;
padding: 10px;
}
.bot {
color: #005393;
float: left;
border-radius: 12px 12px 12px 0px;
}
.user {
float: right;
background-color: #005393;
border-radius: 12px 12px 0px 12px;
color: #fff;
}
#text-response {
height: 23px;
width: 220px;
border-top: 1px solid #eee;
background-color: #fff;
float: left;
}
textarea {
height: 20px;
width: 220px;
float: left;
resize: none;
border: none;
padding: 10px;
line-height: 22px;
font-family: 'Roboto', sans-serif;
font-weight: 200;
letter-spacing: 1px;
font-size: 15px;
outline: none;
overflow: auto;
}
.submit-response {
height: 45px;
width: 80px;
background-color: #005393;
color: #fff;
float: right;
text-align: center;
line-height: 42px;
font-family: 'Roboto', sans-serif;
font-weight: 200;
letter-spacing: 1px;
font-size: 15px;
outline: none;
border: 0;
}
.submit-response:hover {
opacity: 0.5;
}
jQuery
$(document).ready(function() {
$('.submit-response').click(function() {
var $newMessage = $('textarea[name=text-response]').val()
$('#message-feed').append($newMessage, 'message', 'bubble', 'user');
});
});
2 problems over there :
1/ You're not preventing the event default behavior. That means whenever you're clicking on the button which is a submit input, it will send a POST request. So the page will change. To prevent this :
$('.submit-response').click(function() {
var $newMessage = $('textarea[name=text-response]').val();
$('#message-feed').append($newMessage, 'message', 'bubble', 'user');
});
should become :
$('.submit-response').click(function(event) {
event.preventDefault(event);
var $newMessage = $('textarea[name=text-response]').val();
$('#message-feed').append($newMessage, 'message', 'bubble', 'user');
});
2/ You're not actually adding the classes. $.append appends elements, not classes. So :
$('.submit-response').click(function(event) {
event.preventDefault(event);
var $newMessage = $('textarea[name=text-response]').val()
$('#message-feed').append($newMessage, 'message', 'bubble', 'user');
});
should become :
$('.submit-response').click(function(event) {
event.preventDefault(event);
var $newMessageText = $('textarea[name=text-response]').val(),
$newMessage = $('<span class="message bubble user">' + $newMessageText + '</span>');
$('#message-feed').append($newMessage);
});
Now obviously it doesn't have to be a span, it could be anything else. It still has to be an element.
Also, this is only resolving the issues you had on the front end. You'll need AJAX to send the POST to the server side and get the data without refreshing/leaving the page. But that's another topic.

Categories

Resources