I want to make a to do list with HTML, CSS and JS but I can not add delete function. I wanna hold these tasks in localStorage at the same time. When I click second item's delete button, always first item gets deleted. What can I do?
Basically, I want to seperate li's with [data-text=tasklist[i] and delete the li item that has attribute or when clicked.
HTML:
<!DOCTYPE html>
<html lang="tr">
<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" />
<link rel="stylesheet" href="css/style.css" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous"
/>
<link rel="shortcut icon" href="#">
<title>To Do List</title>
</head>
<body>
<!-- Toast start Task -->
<div class="position-fixed bottom-0 right-0 p-3"
style="z-index: 5; right: 0; top: 0;">
<div id="liveToast" class="toast hide" role="alert" aria-live="assertive"
aria-atomic="true" data-delay="6000">
<div class="toast-header">
<strong class="mr-auto">Kodluyoruz </strong>
<span id="toast-img"></span>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body font-weight-bold">
</div>
</div>
</div>
<!-- Toast End For task -->
<!-- Container Start -->
<div class="container col-sm-8 mt-5">
<div class="row text-center d-block">
<!-- Header Start -->
<div class="header my-3 rounded ">
<img
src="https://cdn.sanity.io/images/9kdepi1d/production/65c832d202a503b15d99e628f4313782f3ef50db-300x62.png"
class="mb-1"
alt=""
/>
<h2>To Do List</h2>
<div id="searchBar" class="input-group">
<input class="input-group rounded-left d-inline" type="text"
name="task" id="task" placeholder="Bugün ne yapacaksın?" />
<div class="input-group-append">
<button class="btn btn-primary" onclick="newElement()" id="liveToastBtn">Ekle</button>
</div>
</div>
</div>
<!-- Header End -->
<!-- Task List Start -->
<ul class="list-group" id="list">
</ul>
<!-- Task List End -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script src="js/app.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"
></script>
</div>
</div>
<!-- Container End -->
</body>
</html>
JS:
var TASK = document.querySelector('#task');
let ulEl = document.querySelector('#list');
const toastEl = document.querySelector('#liveToast');
const toastBody = document.querySelector('.toast-body');
const toastImg = document.querySelector('#toast-img');
let collapseBtn = `<button id="clsBtn" onclick="deleteTask()" type="button" class="close"
data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>`
let taskList = !localStorage.getItem('tasks') ? [] : (localStorage.getItem('tasks').split(','));
console.log(taskList)
console.log(taskList.length)
// get the list of tasks in local storage
if(taskList.length>0){
for (let i=0; i < taskList.length; i++) {
if(checkForText(taskList[i])){
TASK.value = taskList[i];
const liDOM = document.createElement('li');
liDOM.innerHTML = `${TASK.value} ${collapseBtn}`;
liDOM.classList.add('list-group-item','d-flex',
'justify-content-between', 'align-items-center');
liDOM.setAttribute('data-text',TASK.value);
ulEl.append(liDOM);
TASK.value = '';
}
}
}
// check for <text> is in the list?
function checkForText(text) {
let found = false;
if(taskList.includes(text.toLowerCase())) {
found = true;
}
return found;
}
// add new Task
function newElement (){
console.log(TASK.value);
console.log("running");
const liDOM = document.createElement('li');
if (TASK.value.length > 0){
if(checkForText(TASK.value)){
//toast
toastBody.innerHTML = `<p class= "text-danger">
Eklemek istediğiniz görev listede mevcut!!</p>`
toastImg.innerHTML = `<img id="toastImg" style="width: 5px;"
src="img/exclamation-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
TASK.value= '';
}else{
liDOM.innerHTML = `${TASK.value} ${collapseBtn}`;
liDOM.classList.add('list-group-item','d-flex',
'justify-content-between', 'align-items-center');
liDOM.setAttribute('data-text',TASK.value);
ulEl.append(liDOM);
taskList.push(TASK.value.trim());
localStorage.setItem('tasks',(taskList));
//************************************ */
// toast
toastBody.innerHTML = `<p class= "text-success">Görev listeye eklendi.</p>`;
toastImg.innerHTML = `<img id="toastImg" style="width: 15px;"
src="img/check-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
TASK.value= '';
}
}else if (TASK.value.length <1 ){
// toast
toastBody.innerHTML = `<p class= "text-danger">Listeye boş ekleme yapamazsınız!!</p>`
toastImg.innerHTML = `<img id="toastImg" style="width: 5px;"
src="img/exclamation-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
// toastEl.classList.replace('hide', 'show');
// await sleep (7000);
// toastEl.classList.replace( 'show', 'hide');
}
}
// delete Task
//if(localStorage.getItem('tasks').length > 0 || taskList.length > 0 ){
function deleteTask(){
let liEl = document.querySelectorAll('.list-group-item');
let i = 0;
for(; i < taskList.length; i++){
if(liEl("data-text") === taskList[i]){
// taskList.splice(taskList.indexOf(taskList[i]), 1);
// liEl.querySelector(`[data-text="${taskList[i]}"]`).removeChild();
console.log( "attr"+liEl.getAttribute("data-text"));
localStorage.setItem('tasks', taskList);
// console.log(taskList);
// console.log(localStorage.getItem('tasks'))
}
}
}
CSS:
* {
box-sizing: border-box;
}
ul {
margin: 0;
padding: 0;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
background: #eee;
font-size: 18px;
transition: 0.2s;
list-style-type: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
ul li:nth-child(odd) {
background: #f9f9f9;
}
ul li:hover {
background: #ddd;
}
ul li.checked {
background: #276678;
color: #fff;
text-decoration: line-through;
}
ul li.checked::before {
content: "";
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #f78501;
color: white;
}
.header {
background-color: #f78501;
padding: 30px 40px;
color: white;
text-align: center;
}
img {
background-color: white;
}
.header:after {
content: "";
display: table;
clear: both;
}
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
.button {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.button:hover {
background-color: #bbb;
}
#task {
width: 94%;
}
I found the solution if anyone need.
Firstly, i create a node list with css attribute selector. (line 98 app.js)
Then i added event listener with for loop (line 100 app.js)
Only bad side of this solution, page have to reload with 'location.reload' function when add a new task. Here all codes:
var TASK = document.querySelector('#task');
let ulEl = document.querySelector('#list');
const toastEl = document.querySelector('#liveToast');
const toastBody = document.querySelector('.toast-body');
const toastImg = document.querySelector('#toast-img');
let collapseBtn = `<button data-delete="cls" class= "Btn rounded small border-secondary" type="button" class="close"
data-dismiss="alert" aria-label="Close">
<span class=" font-weight-bold" aria-hidden="true">×</span>
</button>`
let taskList = !localStorage.getItem('tasks') ? [] : (localStorage.getItem('tasks').split(','));
console.log(taskList)
console.log(taskList.length)
//get the list of tasks in local storage
if(taskList.length>0){
for (let i=0; i < taskList.length; i++) {
if(checkForText(taskList[i])){
TASK.value = taskList[i];
const liDOM = document.createElement('li');
liDOM.innerHTML = `<p>${TASK.value}</p> ${collapseBtn}`;
liDOM.classList.add('list-group-item','d-flex',
'justify-content-between', 'align-items-center');
liDOM.setAttribute('data-text',TASK.value);
ulEl.append(liDOM);
TASK.value = '';
}
}
}
//check for 'text' is in the list?
function checkForText(text) {
let found = false;
if(taskList.includes(text.toLowerCase())) {
found = true;
}
return found;
}
//Add new Task
async function newElement (){
console.log(TASK.value);
console.log("running");
const liDOM = document.createElement('li');
if (TASK.value.length > 0){ //if value length is greater than zero
if(checkForText(TASK.value)){ //if value is already in the list
//toast
toastBody.innerHTML = `<p class= "text-danger">
Eklemek istediğiniz görev listede mevcut!!</p>`
toastImg.innerHTML = `<img id="toastImg" style="width: 5px;"
src="img/exclamation-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
TASK.value= '';
}else{ //if value is not in the list, add it to the list
liDOM.innerHTML = `<p>${TASK.value}</p> ${collapseBtn}`;
liDOM.classList.add('list-group-item','d-flex',
'justify-content-between', 'align-items-center');
liDOM.setAttribute('data-text',TASK.value);
ulEl.append(liDOM);
taskList.push(TASK.value.trim());
localStorage.setItem('tasks',(taskList));
//************************************ */
//toast
toastBody.innerHTML = `<p class= "text-success">Görev listeye eklendi.</p>`;
toastImg.innerHTML = `<img id="toastImg" style="width: 15px;"
src="img/check-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
TASK.value= '';
//working like sleep function
await new Promise(done => setTimeout(() => done(), 3000));
//reload page for close button - addEventListener(deleteTask)
location.reload();
}
}else if (TASK.value.length <1 ){ // if value length is smaller than one
// toast
toastBody.innerHTML = `<p class= "text-danger">Listeye boş ekleme yapamazsınız!!</p>`
toastImg.innerHTML = `<img id="toastImg" style="width: 5px;"
src="img/exclamation-solid.svg" class="rounded mr-2" alt="">`
//Showing and Hiding Toast automatically -JQuery
$(document).ready(function(){
$('#liveToast').toast('show');
});
// toastEl.classList.replace('hide', 'show');
// await sleep (4000);
// toastEl.classList.replace( 'show', 'hide');
}
}
//Delete Task
if(taskList.length > 0 ){
let clsBtn = document.querySelectorAll(`[data-delete="cls"]`)
let i = 0;
for(; i < clsBtn.length; i++){
clsBtn[i].addEventListener('click', deleteTask)
}
function deleteTask(){
let txt = this.parentElement.querySelector('p')
taskList.splice(taskList.indexOf(txt.innerText),1);
this.parentElement.remove();
localStorage.setItem('tasks',taskList);
}
}
Related
I need to add new divs when I click on the (+ Add Element) button, where this button will add new divs to each new click.
Elements with a ('.zone div') need to execute the hover function, but this does not happen, the function does not work on new elements added by the (+ Add Element) button.
Obs. I can't just use CSS class, I need the hover function to work through javascript.
How do I solve this question, so that every new div created by the button (+ Add Element) can work with the hover function?
function addElemnt(){
var div = document.createElement('div');
div.innerHTML = 'Hi there - Element!';
div.className = 'box m-2';
document.querySelector('.zone').appendChild(div);
}
let hover = document.querySelectorAll('.zone div');
for (let elem of hover) {
elem.addEventListener('mouseenter', () => {
elem.style.backgroundColor = 'red'
})
elem.addEventListener('mouseleave', () => {
elem.style.backgroundColor = ''
})
};
.box, .zone{
transition: .4s;
}
.zone{
padding: 16px;
background: #bdbdbd21;
min-width: 282px;
min-height: 200px;
}
.box{
cursor: move !important;
padding: 16px;
box-shadow: 0 2px 2px -1px #a0a0a0cc;
width: 250px;
margin-bottom: 10px;
border-radius: 4px;
font-weight: 600;
font-size: 18px;
background-color: #FFF;
}
.status{
width: 30px;
height: 8PX;
background: gray;
margin-bottom: 16px;
border-radius: 8px;
}
.status.red{
background: red;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<h1>Hello!</h1>
<div class="container text-center">
<div class="row">
<div class="col p-3" style="background-color: silver;">
<a class="btn btn-primary" onclick="addElemnt()" role="button">+ Add Element</a>
</div>
<div class="col-8 zone">
<div class="box m-2">Hi there - 01!</div>
<div class="box m-2">Hi there - 02!</div>
</div>
</div>
</div>
</body>
</html>
You can use event delegation on the .zone element.
let zone = document.querySelector('.zone');
zone.addEventListener('mouseenter', e => {
if (e.target.matches('.box')) e.target.style.backgroundColor = 'red';
}, true);
zone.addEventListener('mouseleave', e => {
if (e.target.matches('.box')) e.target.style.backgroundColor = '';
}, true);
function addElemnt() {
var div = document.createElement('div');
div.innerHTML = 'Hi there - Element!';
div.className = 'box m-2';
document.querySelector('.zone').appendChild(div);
}
let zone = document.querySelector('.zone');
zone.addEventListener('mouseenter', e => {
if (e.target.matches('.box')) e.target.style.backgroundColor = 'red';
}, true);
zone.addEventListener('mouseleave', e => {
if (e.target.matches('.box')) e.target.style.backgroundColor = '';
}, true);
.box,.zone{padding:16px;transition:.4s}.zone{background:#bdbdbd21;min-width:282px;min-height:200px}.box{cursor:move!important;box-shadow:0 2px 2px -1px #a0a0a0cc;width:250px;margin-bottom:10px;border-radius:4px;font-weight:600;font-size:18px;background-color:#fff}.status{width:30px;height:8PX;background:gray;margin-bottom:16px;border-radius:8px}.status.red{background:red}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<h1>Hello!</h1>
<div class="container text-center">
<div class="row">
<div class="col p-3" style="background-color: silver;">
<a class="btn btn-primary" onclick="addElemnt()" role="button">+ Add Element</a>
</div>
<div class="col-8 zone">
<div class="box m-2">Hi there - 01!</div>
<div class="box m-2">Hi there - 02!</div>
</div>
</div>
</div>
I am creating a simple bug tracker that uses a modal to pop up different bugs. The problem I have is that when I delete a bug, there is a thin grey box where the background of the modal was. So basically the list of bugs is empty but it shows the background of the modal even when it should not be there. For example , if you load up the files and open with live server; create a new bug, then delete the bug, you will see the grey box where the bug was just at. I am trying to have the background not be there, when there is no bugs in the list. Any help is greatly appreciated.
I have tried changing the opacity of the modal and issuesList as well as background color, but tbh I am completely lost on how to dynamically change the opacity.
Index.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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<script src="https://kit.fontawesome.com/4582c8b826.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<title>Issue Tracker</title>
</head>
<body>
<div class="contaienr">
<h1>Issue Tracker</h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueinputform">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select class="form-control" id="issueSeverity">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button id="add-issue" onclick="submitIssue()" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="emptyField" tabindex="-1" role="dialog" aria-labelledby="emptyFieldLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="emptyFieldLabel">Invalid Input!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Please provide the desciption of the issue and also the person name who you want to assign the issue.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
app.js
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
if ((description.length == 0) || (assignedTo.length == 0)) {
alert("Please fill all fields with required data.");
document.getElementById('add-issue').setAttribute("data-toggle", "modal");
document.getElementById('add-issue').setAttribute("data-target", "#emptyField")
}
else {
document.getElementById('add-issue').removeAttribute("data-toggle", "modal");
document.getElementById('add-issue').removeAttribute("data-target", "#emptyField")
const issue = { id, description, severity, assignedTo, status };
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
currentIssue.description = `<strike>${currentIssue.description}</strike>`
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => ((issue.id) != id))
localStorage.removeItem('issues');
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (let i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3> ${description} </h3>
<p><i class="fa-solid fa-bolt"></i> ${severity}</p>
<p><i class="fa-solid fa-user"></i> ${assignedTo}</p>
<button onclick="closeIssue(${id})" class="btn btn-warning">Close</button>
<button onclick="deleteIssue(${id})" class="btn btn-danger">Delete</button>
</div>`;
}
}
fetchIssues();
styles.css
*{
box-sizing: border-box;
}
.jumbotron{
background: rgb(225, 224, 224);
margin-top: 20px;
margin-left: 150px;
margin-right: 150px;
padding-left: 60px;
padding-right: 60px;
padding-top: 50px;
padding-bottom: 50px;
border-radius: 6px;
}
.container{
}
p{
margin: 0 0 10px;
}
h1{
font-size: 36px;
margin-top: 20px;
margin-bottom: 10px;
margin-left: 150px;
}
/* .col-lg-12{
display: block;
font-size: 14px;
line-height: 1.42857143;
color: #333;
} */
#issuesList{
padding-top: 40px;
padding-left: 20px;
padding-right: 20px;
padding-bottom: 20px;
display: block;
margin-left: 170px;
margin-right: 170px;
margin-top: 40px;
margin-bottom: 20px;
background-color: rgb(233, 233, 233);
border-radius: 6px;
border: solid grey transparent ;
border-width: thin;
}
h6{
font-size: 12px;
font-family: inherit;
margin-bottom: 10px;
}
h3{
margin-bottom: 10px;
margin-top: 30px;
font-weight: 500;
line-height: 1.1;
}
.label{
background-color: #5bc0de;
border: solid rgb(10, 198, 240);
border-radius: 0.25em;
padding: 3px;
color: white;
line-height: 1;
font-weight: 700;
font-size: 75%;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
#add-issue{
margin-top: 20px;
}
.container::after{
clear: both
}
.modal
{
opacity:0.5 !important;
}
Hello I'm developing a budget app following a tutorial via Coding Addict, I'm having trouble with the submitExpenseForm of the code. It's suppose to work when the user submit multiple "expenses" the problem after the first values the "expense.title" & "expense.amount" has been appended to the html the 2nd+ of the entries for the expense form of the app keeps showing up as undefined and NaN and it's been wrecking my brain for the past two days with rewatching the video, research and coming up with some other codes that didn't work. Any tips would be greatly helpful, thank you so much.
//JS tutorial from freecodecamp.org
// window.alert("javascript is loaded and ready!");
class UI {
//setting variables
constructor() {
this.budgetFeedback = document.querySelector(".budget-feedback");
this.expenseFeedback = document.querySelector(".expense-feedback");
this.budgetForm = document.getElementById("budget-form");
this.budgetInput = document.getElementById("budget-input");
this.budgetAmount = document.getElementById("budget-amount");
this.expenseAmount = document.getElementById("expense-amount");
this.balance = document.getElementById("balance");
this.balanceAmount = document.getElementById("balance-amount");
this.expenseForm = document.getElementById("expense-form");
this.expenseInput = document.getElementById("expense-input");
this.amountInput = document.getElementById("amount-input");
this.expenseList = document.getElementById("expense-list");
this.itemList = [];
this.itemID = 0;
}
//submit button budget, function will run the following code
submitBudgetForm(){
// console.log('hello from es6');
const value = this.budgetInput.value;
if(value === '' || value <0){
this.budgetFeedback.classList.add('showItem');
this.budgetFeedback.innerHTML = `<p>field can't be empty or negative.</p>`;
console.log('error message will appear on DOM');
}
else{
this.budgetAmount.textContent = value;
this.budgetInput.value = "";
this.showBalance();
}
}
//show balance
showBalance(){
const expense = this.totalExpense();
//parseInt would convert argument into a string (string of numbers with no [,]).
const total = parseInt(this.budgetAmount.textContent) - expense;
this.balanceAmount.textContent = total;
if(total < 0){
this.balance.classList.remove("showGreen", "showBlack");
this.balance.classList.add("showRed")
}
else if(total > 0){
this.balance.classList.remove("showRed", "showBlack");
this.balance.classList.add("showGreen");
}
else if(total === 0){
this.balance.classList.remove("showRed", "showGreen");
this.balance.classList.add("showBlack");
}
// console.log(`hey I'm getting a hold of 'this' keyword`);
}
//submit expense form function
submitExpenseForm(){
const expenseValue = this.expenseInput.value;
const amountValue = this.amountInput.value;
if(expenseValue === '' || amountValue === '' || amountValue < 0)
{
this.expenseFeedback.classList.add('showItem');
this.expenseFeedback.innerHTML = `<p>field can't be empty or negative.</p>`
}
else {
let amount = parseInt(amountValue);
this.expenseInput = "";
this.amountInput = "";
let expense = {
id:this.itemID,
title:expenseValue,
amount:amount,
}
this.itemID++;
this.itemList.push(expense);
this.addExpense(expense);
this.showBalance();
//show balance
}
}
//add expense
addExpense(expense){
const div = document.createElement('div');
div.classList.add('expense');
div.innerHTML = `<div class="expense-item d-flex justify-content-between align-items-baseline">
<h6 class="expense-title mb-0 text-uppercase list-item">-${expense.title}</h6>
<h5 class="expense-amount mb-0 list-item">${expense.amount}</h5>
<div class="expense-icons list-item">
<a href="#" class="edit-icon mx-2" data-id="${expense.id}">
<i class="fas fa-edit"></i>
</a>
<a href="#" class="delete-icon" data-id="${expense.id}">
<i class="fas fa-trash"></i>
</a>
</div>
</div>
</div>`;
this.expenseList.appendChild(div);
}
//total expense
totalExpense(){
let total = 0;
if(this.itemList.length > 0){
console.log(this.itemList);
}
this.expenseAmount.textContent = total;
return total;
}
}
function eventListeners(){
const budgetForm = document.getElementById('budget-form');
const expenseForm = document.getElementById('expense-form');
const expenseList = document.getElementById('expense-list');
//new UI Class
const ui = new UI()
//budget form submit
budgetForm.addEventListener('submit', function(event){
event.preventDefault();
ui.submitBudgetForm();
});
//expense form submit
expenseForm.addEventListener('submit', function(event){
event.preventDefault();
ui.submitExpenseForm();
})
//expense click (expense value & title edit and trash)
expenseList.addEventListener('click', function(){
})
}
document.addEventListener('DOMContentLoaded', function(){
eventListeners();
})
:root {
--mainWhite: #f5f5f5f5;
--mainDark: #333333;
--mainGreen: #317b22;
--mainRed: #b80c09;
--mainBlue: #05668d;
--mainYellow: yellow;
}
body {
background: var(--mainWhite);
color: var(--mainDark);
}
.budget-feedback,
.expense-feedback {
display: none;
}
.budget-form {
border: 0.15rem solid var(--mainGreen);
padding: 1rem;
border-radius: 0.25rem;
}
.expense-form {
border: 0.15rem solid var(--mainRed);
padding: 1rem;
border-radius: 0.25rem;
}
.budget-submit {
background: transparent;
border: 0.1rem solid var(--mainGreen);
color: var(--mainGreen);
}
.expense-submit {
background: transparent;
border: 0.1rem solid var(--mainRed);
color: var(--mainRed);
}
.expense-submit:hover {
background: var(--mainRed);
color: var(--mainWhite);
}
.budget-submit:hover {
background: var(--mainGreen);
color: var(--mainDark);
}
.budget-input {
border: 0.05rem solid var(--mainGreen) !important;
margin-bottom: 10px;
}
.expense-input {
border: 0.05rem solid var(--mainRed) !important;
}
.expense-group {
margin-bottom: 10px;
}
.expense-amount,
.expense-title {
color: var(--mainRed);
}
.edit-icon {
color: var(--mainBlue);
cursor: pointer;
font-size: 1rem;
text-decoration: none !important;
}
.delete-icon {
color: var(--mainRed);
cursor: pointer;
font-size: 1rem;
text-decoration: none !important;
}
.edit-icon:hover {
color: var(--mainBlue);
}
.delete-icon:hover {
color: var(--mainRed);
}
.showItem {
display: block;
}
.info-title {
font-size: 1.5rem;
}
.budget {
font-size: 1.6rem;
color: var(--mainGreen);
}
.expense {
font-size: 1.6rem;
color: var(--mainRed);
}
.balance {
font-size: 1.6rem;
}
.budget-icon,
.expense-icon,
.balance-icon {
font-size: 2.5rem;
color: var(--mainBlue);
}
.showRed {
color: var(--mainRed);
}
.showGreen {
color: var(--mainGreen);
}
.showBlack {
color: var(--mainDark);
}
#media screen and (min-width: 992px) {
.budget {
font-size: 2.6rem;
color: var(--mainGreen);
}
.expense {
font-size: 2.6rem;
color: var(--mainRed);
}
.balance {
font-size: 2.6rem;
}
.budget-icon,
.expense-icon,
.balance-icon {
font-size: 3.5rem;
color: var(--mainBlue);
}
}
.list-item {
flex: 0 0 33.33%;
text-align: center;
}
.expense-item {
height: 2rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="./fontawesome-free-5.15.2-web/css/all.css">
<link rel="stylesheet" href="./style.css">
<title>UPPERclassman</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<!--title of app-->
<div class="col-11 mx-auto p-3">
<h3 class="UPPERclassman">UPPERclassman</h3>
</div>
<div class="row">
<div class="col-md-5 my-3">
<!--budget alert message-->
<div class="budget-feedback alert alert-danger text-capitalize">budget feedback</div>
<!---budget form-->
<form id="budget-form" class="budget-form">
<h5>Please enter your budget</h5>
<div class="form-group">
<input type="number" class="form-control budget-input" id="budget-input">
</div>
<!--submit button-->
<button type="submit" class="btn text-capitalize budget-submit" id="budget-submit">calculate</button>
</form>
</div>
<div class="col-md-7">
<div class="row my-3">
<div class="col-4 text-center mb-2">
<h6 class="info-title">Budget</h6>
<span class="budget-icon"><i class="fas fa-money-bill-wave fa-2x"></i></span>
<h4 class="mt-2 budget" id="budget"><span>$</span><span id="budget-amount">0</span></h4>
</div>
<div class="col-4 text-center">
<h6 class="info-title">Expense</h6>
<span class="expense-icon"><i class="far fa-credit-card fa-2x"></i></span>
<h4 class="mt-2 expense" id="expense"><span>$</span><span id="expense-amount">0</span></h4>
</div>
<div class="col-4 text-center">
<h6 class="info-title">Balance</h6>
<span class="balance-icon"><i class="fas fa-hand-holding-usd fa-2x"></i></span>
<h4 class="mt-2 balance" id="balance"><span>$</span><span id="balance-amount">0</span></h4>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 my-3">
<div class="expense-feedback alert alert-danger text-capitalize">expense feedback</div>
<form id="expense-form" class="expense-form">
<h5 class="text-capitalize">please enter your expense</h5>
<div class="form-group expense-group">
<input type="text" class="form-control expense-input" id="expense-input">
</div>
<div class="form-group expense-group">
<input type="number" class="form-control expense-input" id="amount-input">
</div>
<button type="submit" class="btn text-capitalize expense-submit" id="expense-submit">add expense</button>
</form>
</div>
<div class="col-md-7 my-3">
<div class="expense-list" id="expense-list">
<div class="expense-list__info d-flex justify-content-between text-capitalize">
<h5 class="list-item">expense title</h5>
<h5 class="list-item">expense value</h5>
<h5 class="list-item"></h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jquery -->
<!-- <script src="js/jquery-3.3.1.min.js"></script> -->
<!-- bootstrap js -->
<!-- <script src="js/bootstrap.bundle.min.js"></script> -->
<!-- script js -->
<script src="budget.js"></script>
</body>
</html>
These two lines:
this.expenseInput = "";
this.amountInput = "";
are clearing your reference to the controls.
Perhaps they should be:
this.expenseInput.value = "";
this.amountInput.value = "";
i'm presently working on a gitHub battle game with JavaScript manipulations. Please, how can i make the "PLAY AGAIN" button restart the game. (Starting All Over Again)
I also want to make the "DIV WITH CONTROL-BUTTON ID" display as block only if data fetch from API was successful.... Thanks
MY CODE IS BELOW:
"use strict";
let user = document.getElementsByClassName('github-username'),
player1 = document.getElementById('player-one'),
player2 = document.getElementById('player-two'),
form1 = document.getElementById('form1'),
form2 = document.getElementById('form2'),
cont1 = document.getElementById('continue1'),
cont2 = document.getElementById('continue2'),
reSelect = document.getElementById('reselect-players'),
playAgain = document.getElementById('play-again'),
initiate = document.getElementById('initiate-battle');
// Function that activate the start button
function getStarted() {
let startPage = document.getElementById('startPage'),
startBtn = document.getElementById('get-started-button');
startBtn.onclick = function() {
startPage.style.display = "none";
player1.style.display = "block";
};
};
getStarted();
// Function that initiates player 1 input
function firstForm() {
player1.style.display = "none";
player2.style.display = "block";
return false;
};
// Function that initiates player 2 input
function secondForm() {
let confirmPage = document.getElementById('confirm-page');
player2.style.display = "none";
confirmPage.style.display = "block";
// Function that fetches users data from input
function fetchUsers() {
let user1, user2;
fetch("https://api.github.com/users/" + user[0].value)
.then(function(response) {
return response.json();
})
.then(function(data) {
// Log the data to the console
console.log(data);
// Cache the data to a variable
user1 = data;
let myUser1 = document.getElementById('user1-container'),
totalScore = (1 * user1.followers + 1 * user1.following + 0.5 * user1.public_repos);
myUser1.innerHTML = `<ul class="user-info">
<p id="firstPlayer"> Player 1 </p>
<li id="score">Score: <span class="totalScr"> ${totalScore}</span> </li>
<li><img class="avatar" src="${user1.avatar_url}"></li>
<li>Name: ${user1.name} </li>
<li>Username: ${user1.login} </li>
<li>Following: ${user1.following} </li>
<li>Followers: ${user1.followers} </li>
<li>Repository: ${user1.public_repos} </li>
</ul>`;
//Make another API call and pass it into the stream
return fetch("https://api.github.com/users/" + user[1].value)
.then(function(response) {
//Get a JSON object from the response
return response.json();
})
})
.then(function(data) {
//Log the data to the console
console.log(data);
// Cache the data to a variable
user2 = data;
//Now that you have both APIs back, you can do something with the data
let myUser2 = document.getElementById('user2-container'),
totalScore2 = (1 * user2.followers + 1 * user2.following + 0.5 * user2.public_repos);
myUser2.innerHTML = `<ul class="user-info">
<p id="secondPlayer"> Player 2 </p>
<li id="score2">Score: <span class="totalScr"> ${totalScore2}</span> </li>
<li><img class="avatar" src="${user2.avatar_url}"></li>
<li>Name: ${user2.name} </li>
<li>Username: ${user2.login} </li>
<li>Following: ${user2.following} </li>
<li>Followers: ${user2.followers} </li>
<li>Repository: ${user2.public_repos} </li>
</ul>`;
})
};
fetchUsers();
setTimeout(function() {
document.getElementById('control-buttons').style.display = "block";
playAgain.style.display = "none";
}, 1500);
return false;
};
//Function that assign users score and winner
initiate.onclick = function() {
document.getElementById("confirm-players").innerHTML = "Winner";
document.getElementById('score').style.display = "block";
document.getElementById('score2').style.display = "block";
initiate.style.display = "none";
reSelect.style.display = "none";
playAgain.style.display = "block";
let totalScr = document.getElementsByClassName("totalScr"),
totalScr1 = parseFloat(totalScr[0].innerText),
totalScr2 = parseFloat(totalScr[1].innerText);
if (totalScr1 > totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Winner";
document.getElementById("secondPlayer").innerHTML = "Loser";
} else if (totalScr1 < totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Loser";
document.getElementById("secondPlayer").innerHTML = "Winner";
} else {
confirm("IT'S A TIE, PLAY AGAIN");
};
};
reSelect.onclick = function() {
confirmPage.style.display = "none";
player1.style.display = "block";
user[0].value = null;
user[1].value = null;
};
playAgain.onclick = function() {
//Make this function start the game again, following the usual pattern
};
body {
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif, cursive;
background-image: url('images/photo.jpg');
background-size: 100%;
background-repeat: no-repeat;
}
input[type=text] {
-moz-box-sizing: border-box;
box-sizing: border-box;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.3);
border: 1px solid #999;
margin: 50px 0 15px;
}
.body-container {
margin: 0;
text-align: center;
}
.body-container p {
font-size: 16px;
padding-bottom: 5px;
}
.head-text {
padding-top: 60px;
margin-bottom: -10px;
font-size: 36px;
}
#confirm-players {
font-size: 30px;
margin: 10px 0 5px;
}
#get-started-button {
font-size: 18px;
font-weight: 10%;
border: none;
width: 150px;
word-spacing: 2px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
.continue-button {
font-size: 18px;
word-spacing: 2px;
border: none;
width: 200px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
#get-started-button:hover,
.continue-button:hover,
#initiate-battle:hover {
background-color: darkgreen;
}
.github-username {
width: 65%;
height: 35px;
padding: 10px;
margin: 20px 0 15px;
}
#score,
#score2 {
font-size: 18px;
font-weight: bolder;
display: none;
text-align: center;
}
#player-one,
#player-two {
display: none;
}
#confirm-page,
#winner {
display: none;
margin: 20px 0 10px;
}
#initiate-battle,
#play-again {
font-size: 18px;
border: none;
width: 200px;
border-radius: 5px;
word-spacing: 2px;
letter-spacing: 0.4px;
height: 40px;
background-color: green;
color: white;
margin: 15px auto 5px;
}
#reselect-players {
font-size: 18px;
border: none;
word-spacing: 2px;
letter-spacing: 0.4px;
width: 240px;
border-radius: 5px;
height: 35px;
background-color: cornflowerblue;
color: white;
margin: 10px auto;
}
#control-buttons {
display: none;
}
#reselect-players:hover {
background-color: darkslateblue;
}
.avatar {
border-radius: 50%;
height: 200px;
width: 200px;
}
.myUsers {
display: inline-block;
margin: 0 5px 0 10px;
}
ul {
margin-left: -30px;
}
li {
list-style: none;
padding: 5px;
text-align: left;
border: 1px solid grey;
}
#firstPlayer,
#secondPlayer {
margin-bottom: 0;
}
<DOCTYPE! html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="githstyle.css" type="text/css">
</head>
<body>
<div id="startPage" class="body-container">
<h1 class="head-text">GitHub Challenge</h1>
<p>Some challenges are worth engaging 🤓</p>
<button id="get-started-button">Get Started</button>
</div>
<div id="player-one" class="body-container">
<h1 class="head-text">Player One</h1>
<div class="form-container">
<form id="form1" onsubmit="return firstForm();">
<div>
<input type="text" class="github-username" placeholder="Enter Player's GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="player-two" class="body-container">
<h1 class="head-text">Player Two</h1>
<div class="form-container">
<form id="form2" onsubmit="return secondForm()">
<div>
<input type="text" name="" class="github-username" placeholder="GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="confirm-page" class="body-container">
<h1 id="confirm-players">Confirm players</h1>
<div id="user1-container" class="myUsers">
</div>
<div id="user2-container" class="myUsers">
</div>
<div id="control-buttons">
<div>
<button id="initiate-battle">Initiate Battle</button>
</div>
<div>
<button id="reselect-players">Reselect Players</button>
</div>
<div>
<button id="play-again">Play Again</button>
</div>
</div>
</div>
<script src="gith.js" type="text/javascript">
</script>
</body>
</html>
Reloading the page using JavaScript is very easy.
You can achieve this by using location.reload()
If you want to achieve reloading using a button, then be sure to add a return false; right after you call location.reload() to prevent bubbling (parents of the button won't know the event occurred).
So, your code will look something like this :
document.getElementById('yourButton').addEventListener('click', function(){
location.reload();
return false;
});
Hope this helps ! :)
I am trying to let the icons (wich will be buttons in the future) stay hidden until the right word is placed in the tab the button is in too, so when it's all done you can only click the icon if you've set the right word in the right tab and some audio will play.. but I can't seem to figure out how to let the icon stay hidden until the word is placed, if I look it up, something needs to stay hidden until the button is clicked, but I don't want that..
This is how it looks
This is my code
$(document).ready(function() {
var rigtige = 0; //good_points
var forkerte = 0; //false_points
var answers;
var footer;
var timer = setInterval(function() {
getReady();
}, 203);
var number = [0, 1, 2, 3, 4, 5, 6, 7];
//define JSON arrays (jsonData_0_123.json)
function getReady() {
if (jsonData !== "noJson") {
clearInterval(timer);
answers = jsonData.answers;
footer = jsonData.footer;
makeWordList();
dragDrop();
}
}
//end
function makeWordList() {
shuffle(number);
var text_time;
for (var j = 0; j < answers.length; j++) {
var i = j + 1;
//<div class="tekst draggable" id="tekst1"> <p>kat</p> </div>
document.getElementById("word" + number[j]).innerHTML = '<div class="tekst draggable" id="tekst' + i + '"> <span>' + answers[j] + '</span></div>'
}
}
// //makeWordList
// function makeWordList() {
// shuffle(number);
// for (var i = 0; i < answers.length; i++) {
// //<div class="tekst draggable" id="tekst1"> <p>kat</p> </div>
// var j = i + 1;
// var str = '<div class="tekst draggable" id="tekst'+ j +'"> <p>'+ answers[i] +'</p> </div>';
// document.getElementById('word' + number[i]).innerHTML = str;
// }
// };
//
// //end
//shuffle
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
//end
//make dragdroppable
function dragDrop() {
//Make the revert event for draggable
$.ui.draggable.prototype._mouseStop = function(event) {
//If we are using droppables, inform the manager about the drop
var dropped = false;
if ($.ui.ddmanager && !this.options.dropBehaviour)
dropped = $.ui.ddmanager.drop(this, event);
//if a drop comes from outside (a sortable)
if (this.dropped) {
dropped = this.dropped;
this.dropped = false;
}
if ((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
var self = this;
self._trigger("reverting", event);
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
event.reverted = true;
self._trigger("stop", event);
self._clear();
});
} else {
this._trigger("stop", event);
this._clear();
}
return false;
}
//end
//Make tekst draggable
$(".draggable").draggable({
opacity: 1,
containment: 'body',
revert: true,
scroll: false,
reverting: function() {
console.log('reverted');
//play('false');
forkerte++;
document.getElementById("forkerte").innerHTML = '<span id="forkerte">' + forkerte + '</span>';
},
});
//end
var id = 1;
var text = "";
var text2 = "";
while (id < 9) { // lengte van je array + 1
text = "antwoord" + id; //id= antwoord1 antwoord2 enz daarom antwoord + id zo dat het er 8 keer komt
text2 = "tekst" + id;
$("#" + text).droppable({ // dan wordt het dus allemaal droppable id antwoord 1 tm 8
tolerance: "pointer",
accept: "#" + text2, // Welke id er op moet vallen je maakt antwoord1a(tekst) bv droppable voor antwoord1(antwoord div)
drop: function(event, ui) {
// play('true');
$(ui.draggable).draggable({
revert: false
}); // Only draggable in div antwoord
$(ui.draggable).draggable('disable'); //disable draggable
ui.draggable.position({
of: $(this),
my: 'center left',
at: 'center center'
});
$(this).droppable('disable');
rigtige++; //+1 bij de punten van goed
document.getElementById("rigtige").innerHTML = '<span id="rigtige">' + rigtige + '</span>'; //update de html
//checckScore();
}
});
id++; //BELANKRIJK zonder id++ endles loop
}
}
//end
//spinning reset button
$(".spin").mouseenter(function() {
$(".fa-refresh").addClass("fa-spin");
});
$(".spin").mouseleave(function() {
$(".fa-refresh").removeClass("fa-spin");
});
// end
});
body,
html {
margin-left: 10%;
margin-right: 10%;
padding: 0px;
height: 100%;
font-family: georgia, "Comic Sans MS";
background-color: #f0f0f0;
}
.container {
height: 90%;
border-collapse: collapse;
display: table;
}
.igen {
font-size: 25px;
font-weight: bold;
}
.points {
float: right;
}
.container {
height: 90%;
border-collapse: collapse;
display: table;
}
header {
height: 5%;
border-bottom: thick solid grey;
}
.img {
width: 25%;
height: 30%;
background-color: #f0f0f0;
float: left;
}
.center {
margin-left: 25%;
margin-right: 25%;
}
.antwoord {
float: left;
width: 95%;
height: 25px;
background-color: white;
border-style: solid;
border-color: #000000;
border-width: 4px;
}
.move2 {
margin-top: 12.5%
}
.move4 {
margin-top: 19%
}
.move5 {
margin-top: 33.5%
}
.move6 {
margin-top: 20.8%
}
.move7 {
margin-top: 37.5%
}
.border {
margin-top: 45%;
border-top: thick solid grey;
background-color: red;
}
.word,
.word .tekst,
.word p {
display: inline;
margin-left: 7%;
font-weight: bold;
}
.my-row {
clear: both;
}
.answers .word,
.answers .word2 {
float: left;
padding: 3px;
margin-left: 7%;
font-weight: bold;
}
.fa {
margin-left: 5px;
margin-top: 2px;
}
.word,
.word2 {
padding-top: 5%;
margin: 5%;
}
footer {
border-top: thick solid grey;
height: 5%;
display: table-row;
vertical-align: bottom;
}
.sprint {
float: right;
}
.copyright {
position: relative;
bottom: 20px;
left: 65px;
font-size: 10px;
}
a {
text-decoration: none;
color: black;
}
a:hover {
text-decoration: none;
color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Words</title>
<link rel="stylesheet" href="style.css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<header>
<span class="fa fa-refresh spin" style="font-size:25px;"></span><span class="igen spin"> igen</span>
<span class="points"><i class="fa fa-thumbs-o-up" style="font-size:24px"></i>Rigtige: <span id="rigtige">0</span> <i class="fa fa-thumbs-o-down" style="font-size:24px"></i>Forkerte:
<span id="forkerte">0</span>
</span>
</header>
<div class="container">
<div class="img" id="img1">
<div class="plaatje" id="plaatje1">
<img class="center" src="img/cat.jpg" alt="cat" width="50%;">
</div>
<div class="move1">
<div class="antwoord droppable" id="antwoord1"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img2">
<div class="plaatje" id="plaatje1">
<img class="center" src="img/beak.jpg" alt="beak" width="50%;">
</div>
<div class="move2">
<div class="antwoord" id="antwoord2"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img3">
<div class="plaatje" id="plaatje3">
<img class="center" src="img/spoon.jpg" alt="spoon" width="50%;">
</div>
<div class="move3">
<div class="antwoord" id="antwoord3"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img4">
<div class="plaatje" id="plaatje4">
<img class="center" src="img/milk.jpg" alt="milk" width="50%;">
</div>
<div class="move4">
<div class="antwoord" id="antwoord4"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img5">
<div class="plaatje" id="plaatje5">
<img class="center" src="img/egg.jpg" alt="egg" width="50%;">
</div>
<div class="move5">
<div class="antwoord" id="antwoord5"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img6">
<div class="plaatje" id="plaatje6">
<img class="center" src="img/thee.jpg" alt="tea" width="50%;">
</div>
<div class="move6">
<div class="antwoord" id="antwoord6"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img7">
<div class="plaatje" id="plaatje7">
<img class="center" src="img/meel.jpg" alt="flour" width="50%;">
</div>
<div class="move7">
<div class="antwoord" id="antwoord7"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="img" id="img8">
<div class="plaatje" id="plaatje8">
<img class="center" src="img/passport.jpg" alt="passport" width="50%;">
</div>
<div class="move8">
<div class="antwoord" id="antwoord8"><i class="fa fa-play" style="font-size:20px"></i>
</div>
</div>
</div>
<div class="answers">
<div class="my-row border">
<div class="word" id="word0"></div>
<div class="word" id="word1"></div>
<div class="word" id="word2"></div>
<div class="word" id="word3"></div>
</div>
<div class="my-row">
<div class="word2" id="word4"></div>
<div class="word2" id="word5"></div>
<div class="word2" id="word6"></div>
<div class="word2" id="word7"></div>
</div>
</div>
<footer>
<img class="dansk" id="dansk" src="img/dansk2.jpg" alt="dansk" />
<img class="sprint" id="sprint" src="img/sprint2.png" alt="sprint" />
<center><span class="copyright"> ©2013 laerdansk / FC-Sprint² Leerbedrijf bronnen </span>
</center>
</footer>
<script type="text/javascript">
var jsonData = "noJson";
var hr = new XMLHttpRequest();
hr.open("GET", "json_files/jsonData_0_123.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
jsonData = JSON.parse(hr.responseText).main_object;
}
}
hr.send(null);
</script>
<script src="javascript.js"></script>
</body>
</html>
this is my fiddle i hope it's okay since it's the second time making a fiddle
if it's not right, please, tips are always welcome! https://jsfiddle.net/82332Lk8/
you would be able to do this with the accept option within droppable.
But first, you need to declare the image's visibility as "hidden" in your css file:
.eggImage {
visibility: hidden;
}
once you make the matching word draggable with a class like '.wordEgg' then you could use 'accept' in your droppable function to specify which class the droppable element accepts, then use css() to change the visibility of the image:
$( ".eggImage" ).droppable({
accept: ".wordEgg",
drop: function() {
$(".eggImage").css("visibility","visible")
});
working fiddle demo: http://jsfiddle.net/drrrreams/7q74ophg/