I'm creating a to-do list and I have a constructor function for creating the list items. Each time the user hits enter in the input field I want a new task element to be created just below the first one. As of now, I've tried several methods: looping through the constructor function and looping through the individual command that gives the position of the element within the constructor function.
let addTask = document.getElementById('addItem');
addTask.value = '';
let items = [];
let taskBG;
let taskText;
function Task(){
taskBG = document.createElement('div');
taskBG.style.height = '60px';
taskBG.style.width = '800px';
taskBG.style.marginTop = '-680px';
taskBG.style.marginLeft = '502px';
taskBG.style.backgroundColor = 'red';
taskText = document.createElement('div');
taskText.style.position = 'absolute';
taskText.style.marginTop = '-680px';
taskText.style.marginLeft = '550px';
taskText.style.fontSize = '50px';
taskText.style.fontWeight = 'bold';
taskText.style.color = 'lightgrey';
taskBG.appendChild(taskText);
document.body.appendChild(taskText);
document.body.appendChild(taskBG);
};
addTask.addEventListener('keydown', (ev) => {
if(ev.keyCode == 13){
items.push(addTask.value);
new Task();
addTask.value = '';
for(let i=0; i < items.length; i++){
taskText.textContent = items[i];
};
};
});
body {
background-image:url(backg.jpg);
background-size:2400px, 2400px;
}
#mainBG {
height:900px;
width:900px;
background-color:rgb(72, 73, 73);
opacity:0.6;
display:grid;
margin:0 auto;
}
#mainTitle {
display:grid;
margin:0 auto;
height:100px;
width:700px;
background-color:black;
border-radius:10px;
}
#mainText {
color:white;
font-weight:bold;
display:grid;
margin:0 auto;
font-size:70px;
font-family:"Arial Black", Gadget, sans-serif;
}
#addItem {
display:grid;
margin:0 auto;
height:30px;
width:400px;
margin-top:-360px;
border-radius:10px;
background-color:rgb(128, 201, 201);
color:white;
font-weight:bold;
font-family:"Arial Black", Gadget, sans-serif;
font-size:20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> To-Do </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mainBG">
<div id="mainTitle">
<div id="mainText">To-Do</div>
</div>
<input id="addItem" type="text" placeholder="Add a Task!">
</div>
<script src="app.js"></script>
</body>
</html>
Try this:
let addTask = document.getElementById('addItem');
addTask.value = '';
let items = [];
let taskBG;
let taskText;
var totalTasks = 0;
function Task(){
taskBG = document.createElement('div');
taskBG.style.height = '60px';
taskBG.style.width = '800px';
if (totalTasks == 0) {
taskBG.style.marginTop = '-680px';
}
taskBG.style.marginLeft = '502px';
taskBG.style.backgroundColor = 'red';
taskText = document.createElement('div');
taskText.style.position = 'absolute';
if (totalTasks == 0) {
taskText.style.marginTop = '-680px';
}
taskText.style.marginLeft = '550px';
taskText.style.fontSize = '50px';
taskText.style.fontWeight = 'bold';
taskText.style.color = 'lightgrey';
taskBG.appendChild(taskText);
document.body.appendChild(taskText);
document.body.appendChild(taskBG);
if (totalTasks == 0) {
totalTasks = 1;
}
};
addTask.addEventListener('keydown', (ev) => {
if(ev.keyCode == 13){
items.push(addTask.value);
new Task();
addTask.value = '';
for(let i=0; i < items.length; i++){
taskText.textContent = items[i];
};
};
});
body {
background-image:url(backg.jpg);
background-size:2400px, 2400px;
}
#mainBG {
height:900px;
width:900px;
background-color:rgb(72, 73, 73);
opacity:0.6;
display:grid;
margin:0 auto;
}
#mainTitle {
display:grid;
margin:0 auto;
height:100px;
width:700px;
background-color:black;
border-radius:10px;
}
#mainText {
color:white;
font-weight:bold;
display:grid;
margin:0 auto;
font-size:70px;
font-family:"Arial Black", Gadget, sans-serif;
}
#addItem {
display:grid;
margin:0 auto;
height:30px;
width:400px;
margin-top:-360px;
border-radius:10px;
background-color:rgb(128, 201, 201);
color:white;
font-weight:bold;
font-family:"Arial Black", Gadget, sans-serif;
font-size:20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> To-Do </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mainBG">
<div id="mainTitle">
<div id="mainText">To-Do</div>
</div>
<input id="addItem" type="text" placeholder="Add a Task!">
</div>
<script src="app.js"></script>
</body>
</html>
I have just added totalTasks var with the value of 0 and in task() function I am checking if the variable is 0 then add marginTop otherwise do not add it. As marginTop only needed in the first task for the remaining it doesn't be needed.
Related
when I click in the button the backgrounf color of the change but after one seconde it disappear
this is the code
<!DOCTYPE html>
<html>
<head>
<title>ex7</title>
<meta charset="utf-8">
<script>
function changerCouleur() {
document.bgColor= "#FFFggF";
}
</script>
</head>
<body>
<form>
couleur <input type="text" > <br>
<button onclick="changerCouleur()">changer couleur </button>
</form>
</body>
</html>
I see you already have an answer, but there is no localStorage mechanism with that example. You may want to study the following structure.
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{ // load
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
// small Library above - magic below can be put on another page using a load event *(except the // end load line)*
const bg = I('bg'), ch_bg = I('ch_bg'), gut = I('gut'), gutS = gut.style;
bg.oninput = function(){
if(this.value.trim().length < 3){
rC(this, 'good');
}
else{
aC(this, 'good');
}
}
ch_bg.onclick = ()=>{
if(hC(bg, 'good')){
let color = bg.value.trim();
bg.value = color; gutS.backgroundColor = color; localStorage.bgColor = color;
}
}
if(localStorage.bgColor){
gutS.backgroundColor = localStorage.bgColor;
}
else{
localStorage.bgColor = '#aaa';
}
}); // end load
//]]>
/* css/external.css */
*{
padding:0; margin:0; font-size:0; border:0; box-sizing:border-box; outline:none; overflow:hidden; -webkit-tap-highlight-color:transparent;
-moz-user-select:none; -ms-user-select:none; -webkit-user-select:none; user-select:none;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#aaa;
}
.bar{
position:relative; width:100%; height:39px; background:#ccc; padding:3px; border-bottom:1px solid #333;
}
.bar>*{
position:relative; display:inline-block; height:32px;
}
.bar>*>img{
width:32px; height:32px;
}
.bar h1{
font:bold 27px Tahoma, Geneva, sans-serif; margin-left:3px;
}
.guts{
width:100%; max-height:calc(100% - 39px); background:#aaa; padding:7px 7px 0; overflow-y:auto;
}
.guts *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
label>span{
cursor:pointer; display:inline-block; height:27px; color:#fff; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; float:left;
}
label>input,label>select,label>textarea{
width:100%; height:38px; background:#fff; color:#000; padding:5px; border:1px solid #c00; border-radius:3px; box-shadow:none; margin:2px 0 5px 0; -moz-user-select:text; -ms-user-select:text; -webkit-user-select:text; user-select:text;
}
label>input.good,label>select.good,label>textarea.good{
border-color:#0c0;
}
label>textarea{
height:auto;
}
label>input[type=button],label>button{
cursor:pointer; height:auto; background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 28px Tahoma, Geneva, sans-serif; border:1px solid #007; border-radius:10px;
}
#ch_bg{
margin-bottom:7px;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div class='bar'><h1>Color Change Example</h1></div>
<div class='guts' id='gut'>
<label><span>couleur</span><input id='bg' type='text' value='' /><input id='ch_bg' type='button' value='changer couleur' /></label>
</div>
</div>
</body>
</html>
#FFFggF is not a valid color code.
Please try this code:
function changerCouleur() {
document.body.style.background = "#ff9933";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>ex7</title>
<meta charset="utf-8">
</head>
<body>
<form onSubmit="return false">
couleur <input type="text" > <br>
<button onclick="changerCouleur();">changer couleur </button>
</form>
</body>
</html>
I added the attribute onSubmit="return false" to the form because otherwise every time you click on the button the page is reloaded
When I select and drag and drop multiple files in the drop files area, it goes to Uploads folder but I see only one item under the drop files area each time when uploading.
I want to show multiple files instead of one file/item under the drop files area when uploading.
How can I do that?
if(file_exists($serverpath)) is not working. I don't know why.
Can you people look into it?
I want the same uploaded file rename from 0 to 1,2,3 when I upload files when files exist(if(file_exists($serverpath))) in Uploads folder.
When I click on a image it shows a image box.
I need the .Crop-Box resizable and draggable.
I am using mozilla firefox and google chrome.
Here is the code:
*{margin:0; padding:0;}
body{background:black;}
#Container{
margin:200px auto;
width:620px;
padding-bottom:20px;
background:#ffffff;
color:black;
border:1px solid gray;
border-radius:5px;
}
#Text{
margin:20px;
color:green;
font-family:verdana;
font-size:12pt;
}
#Drop{
margin:20px auto;
padding:20px;
color:gray;
width:500px;
height:40px;
background:#f1f1f1;
border:1px dotted #ccc;
border-radius:5px;
}
.progressbar{
margin:20px auto;
width:80%;
height:20px;
background:#ddd;
border-radius:5px;
display:none;
}
.progress{
width:0%;
height:20px;
border-radius:5px;
background:linear-gradient(to bottom, lightblue, #2196f3);
}
.progresstext{
float:right;
}
.InsertInto{
margin-top:20px;
}
.image{
margin:20px;
width:15%;
height:20%;
display:none;
}
.FileDiv{
margin-bottom:20px;
}
.filenam{
position:absolute;
margin-top:-57px;
margin-left:140px;
}
#RealFile{
margin:20px;
display:none;
}
#UploadImage{
margin-left:100px;
padding:20px 200px;
background:#2196f3;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}
button:focus{
outline:none;
}
#Submit{
margin-left:100px;
padding:20px 200px;
background:#219549;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}
.Crop-Main{
position:relative;
width:600px;
min-width:600px;
height:520px;
margin:100px auto;
padding:20px;
background:#f1f1f1;
color:black;
border:1px solid #ccc;
border-radius:5px;
z-index:1;
display:none;
}
#Close{
background:#2196f3;
color:white;
padding:10px;
font-family:verdana;
font-size:12pt;
cursor:pointer;
border-radius:5px;
margin:20px;
margin-right:0px;
float:right;
user-select:none;
}
.Crop-Container{
position:relative;
width:600px;
margin:80px auto;
min-height:300px;
}
.Crop-Container img{
width:600px;
user-select:none;
}
.Crop-Box{
position:absolute;
width:200px;
height:200px;
top:0;
left:0;
background:rgba(69,69,69,0.6);
border:1px solid white;
z-index:2;
cursor:move;
}
#Save{
position:absolute;
padding:20px 80px;
background:green;
color:white;
border:none;
border-radius:5px;
font-family:verdana;
font-size:12pt;
cursor:pointer;
margin:-70px 200px;
}
.InsertInto img{
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="jquery.min.js"></script>
<body>
<div class="Crop-Main">
<span id="Close">X</span>
<div class="Crop-Container">
<img src=""/>
<div class="Crop-Box"></div>
</div>
<button id="Save" onclick="save()">Save</button>
</div>
<div id="Container">
<div id="Text">Advanced File Uploader</div>
<div id="Drop">Drop files here</div>
<div class="progressbar">
<div class="progress"></div>
<div class="progresstext">0%</div>
</div>
<div class="InsertInto">
</div>
<input type="file" name="realfile" id="RealFile" multiple="true"><br/><br/>
<button id="UploadImage" type="button">Upload</button>
<br/><br/>
<form action="uploads.php" method="POST" id="myForm" enctype="multipart/form-data">
<input type="submit" name="submit" id="Submit" value="Submit">
</form>
</div>
<script>
var obj = document.querySelector("#Drop");
var realf = document.querySelector("#RealFile");
obj.ondragover = function(e){
$(this).css("border-color","green");
return false;
}
obj.ondragleave = function(e){
return false;
$(this).css("border","none");
}
obj.ondrop = function(e){
e.preventDefault();
$(this).css("border-color","#2196f3");
var files = e.dataTransfer.files;
upload(files);
console.log(files);
}
realf.onchange = function(e){
var files = e.currentTarget.files;
upload(files);
console.log(files);
}
function upload(e){
var formdata = new FormData();
var xhttp = new XMLHttpRequest();
var i;
for(i=0; i < e.length; i++){
formdata.append("realfile[]", e[i]);
}
if(xhttp.upload){
xhttp.open("POST", "upload.php", true);
xhttp.upload.addEventListener("progress", function(e){
var parcent = (e.loaded / e.total) * 100;
document.querySelector(".progressbar").style.display = "block";
document.querySelector(".progress").style.width = parcent+"%";
document.querySelector(".progresstext").innerHTML = parcent+"%";
});
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
var result;
result = this.responseText;
var newresult = JSON.parse(result);
var i;
document.querySelector(".progressbar").style.display = "none";
var insertinto = document.querySelector(".InsertInto");
var filediv = document.createElement("DIV");
filediv.className = "FileDiv";
insertinto.appendChild(filediv);
var img = document.createElement("IMG");
img.className = "image";
filediv.appendChild(img);
img.setAttribute("src",newresult.url);
img.setAttribute("width","100%");
img.setAttribute("height","100%");
img.style.display = "block";
img.addEventListener("click", function(e){
var cropmain = document.querySelector(".Crop-Main");
cropmain.style.display = "block";
document.querySelector("#Container").style.display = "none";
var imgsrc = $(this).attr("src");
$(".Crop-Container img").attr("src", imgsrc);
});
var close = document.querySelector("#Close");
close.addEventListener("click", function(e){
document.querySelector(".Crop-Main").style.display = "none";
document.querySelector("#Container").style.display = "block";
});
var filenam = document.createElement("DIV");
filenam.className = "filenam";
filenam.innerHTML = newresult.name;
insertinto.appendChild(filenam);
if(newresult != "" && newresult != "Not Ok"){
for(i=0; i<newresult.length; i++){
if(newresult[i].status == true){
}
}
}
console.log(xhttp.responseText);
}
}
xhttp.send(formdata);
}
}
$("#UploadImage").click(function(e){
$("#RealFile").click();
});
$(".InsertInto").on("click", ".InsertInto img", function(){
var img = $(this).attr("src");
$(".Crop-Container").find("img").attr("src", img);
var w = $(".Crop-Container img").width();
var h = $(".Crop-Container img").height();
$(".Crop-Container").width(w);
$(".Crop-Container").height(h);
document.querySelector(".Container").style.display = "none";
document.querySelector(".Crop-Main").style.display = "block";
});
</script>
</body>
</html>
PHP
<?php
$status = array();
$allow = array("image/jpeg", "image/png");
//print "<pre>"
//print_r($_FILES["file"]);
//print "</pre>"
foreach($_FILES["realfile"]["name"] as $pos => $val){
if(!in_array(strtolower($_FILES["realfile"]["type"][$pos]), $allow)){
$status = array(
"name" => $_FILES["realfile"]["name"],
"type" => $_FILES["realfile"]["type"],
"url" => "",
"message" => "Invalid file type",
"status" => false
);
}
else{
$tmpname = $_FILES['realfile']['tmp_name'][$pos];
$filename = $_FILES["realfile"]["name"][$pos];
//$path = "Uploads/".$filename;
$addition = 0;
$serverpath = $_SERVER['DOCUMENT_ROOT']."Uploads/".$filename;
if(file_exists($serverpath)){
while(file_exists($serverpath)){
$addition = $addition + 1;
$info = pathinfo($serverpath);
$directory = $info["dirname"];
$oldname = $info["filename"];
$oldext = $info["extension"];
$serverpath = $directory."/".$oldname.$addition.".".$oldext;
}
$serverpath = "Uploads/".$oldname.$addition.".".$oldext;
}
else{
$serverpath = "Uploads/".$filename;
}
move_uploaded_file($tmpname, $serverpath);
$status = array(
"name" => $_FILES["realfile"]["name"][$pos],
"type" => $_FILES["realfile"]["type"][$pos],
"url" => $serverpath,
"message" => "File Uploaded",
"status" => true
);
}
}
echo json_encode($status);
?>
EDITED MAY, 26TH:
I'm using the coding you'll see below as an answer from #AchrafJEDAY (I'll also include it here as well). The coding as broke somehow, and when I click on the date or tag buttons to show the date or tag for ANY post, it freaks out; you see it for just a moment before the whole page refreshes with "/?" at the end of the URL and the date and tags are both hidden again. I'm not sure why this is, but I'd SUPER appreciate ANY help anyone has! Thank you!!
CODING:
CSS
.postdatebutton{
float:left;
position:relative;
top:0px;
left:0px;
width:50px;
height:15px;
border:1px #83174C solid;
background-color:rgba(255, 230, 240, 0.8);
font-family: 'Indie Flower', cursive;
letter-spacing:2px;
text-align:center;
padding-top:5px;
color:black;
font-size:14px;
text-decoration:underline;
}
.postdatebutton button{
font-family: 'Indie Flower', cursive;
text-decoration:underline;
}
.postdate{
width: 100%;
text-align: center;
display:none;
}
/*TAGS*/
.tags {
width:415px;
text-transform:uppercase;
line-height:120%;
font-size:15px;
text-align:center;
padding:2px;
text-decoration:underline;
-moz-transition-duration:0.5s;
-webkit-transition-duration:0.5s;
-o-transition-duration:0.5s;
}
.tags a {
color:#BB0B20;
letter-spacing:1px;
padding:1px;
}
.posttagbutton{
float:left;
position:relative;
top:0px;
left:0px;
width:50px;
height:15px;
border:1px #83174C solid;
background-color:rgba(255, 230, 240, 0.8);
font-family: 'Indie Flower', cursive;
letter-spacing:2px;
text-align:center;
padding-top:5px;
color:black;
font-size:14px;
text-decoration:underline;
}
.posttagbutton button{
font-family: 'Indie Flower', cursive;
text-decoration:underline;
}
.posttag {
width: 100%;
text-align: center;
display:none;
}
#stuff table{
position:relative;
width:100%;
text-align:center;
}
HTML
<table>
<tbody>
<tr>
<!---LIKE---->
<td><div class="postlike">{LikeButton}</div> </td>
<!---REBLOG---->
<td><div id="postreblog">Reblog</div> </td>
<!---NOTES---->
<td><div class="postnote">{block:NoteCount} Notes{/block:NoteCount}</div> </td>
<!---VIA---->
<td><div class="postfrom">{block:RebloggedFrom}From{/block:RebloggedFrom}</div> </td>
<!---SOURCE---->
<td><div class="postsource"> {block:ContentSource}Orig-Poster{/block:ContentSource}</div> </td>
<!---DATE BUTTON---->
<td><div class="postdatebutton"><button onclick="myFunction6(this)">Date</button></div></td>
<!---TAGS BUTTON---->
<td><div class="posttagbutton"><button onclick="myFunction7(this)">Tags</button></div></td></tr></tbody></table>
<!---HIDDEN DATE---->
<div class="postdate" style="display:none;"><p>{block:Date} {MonthNumberWithZero}-{DayOfMonthWithZero} {24Hour}:{Minutes}{/block:Date}</p></div>
<!---HIDDEN TAGS---->
<div class="posttag" style="display:none;"><div class="tags"><p>{block:Tags}# {Tag}{/block:Tags}</p></div></div>
JS
<!---SCRIPT FOR DATE AND TAGS---->
<script>
function myFunction6 ( event ) {
var node = event.parentNode;
for (i = 0; i < 5; i++) {
node = node.parentNode;
}
var x = node.getElementsByClassName("postdate");
if (x[0].style.display === 'block') {
x[0].style["display"] = "none";
}
else {
x[0].style["display"] = "block";
}
}
</script>
<script>
function myFunction7( event ) {
var node = event.parentNode;
for (i = 0; i < 5; i++) {
node = node.parentNode;
}
var x = node.getElementsByClassName("posttag");
if (x[0].style.display === 'block') {
x[0].style.display = 'none';
}
else {
x[0].style.display = 'block';
}
}
</script>
function myFunction1 ( event ) {
var node = event.parentNode;
for (i = 0; i < 5; i++) {
node = node.parentNode;
}
var x = node.getElementsByClassName("postdate");
if (x[0].style.display === 'block') {
x[0].style["display"] = "none";
}
else {
x[0].style["display"] = "block";
}
}
function myFunction2( event ) {
var node = event.parentNode;
for (i = 0; i < 5; i++) {
node = node.parentNode;
}
var x = node.getElementsByClassName("posttag");
if (x[0].style.display === 'block') {
x[0].style.display = 'none';
}
else {
x[0].style.display = 'block';
}
}
<div id="stuff"><div class="picsize"><div class="textpost"><h3> Testing Text Post - Title </h3><p><span>allystestblog1818</span>:</p><blockquote><h2>Headline</h2><h2><b>Headline Bold</b></h2><h2><i>Headline Italic</i></h2><p><b>Bold text,</b> <i>Italic text,</i> <span>Link text</span></p><ol><li>Numbered <br></li><li>List<br></li></ol><ul><li>Bullet<br></li><li>List<br></li></ul><blockquote><p>Indented text</p></blockquote><p>Regular text</p><p>Line break<br></p><hr><p>Picture</p><figure class="tmblr-full"><img src="https://68.media.tumblr.com/1250d273b9e9b4860d73aa893361ec20/tumblr_inline_oogr5xEk1J1txz9li_540.jpg" class=""></figure><p class=""><span>Keep reading</span></p></blockquote></div></div><div class="picsize"></div><p></p><table><tbody><tr><td><div class="postlike"><div class="like_button" data-post-id="160506016653" data-blog-name="wisdomsprydethemetestblog" id="like_button_160506016653"><iframe id="like_iframe_160506016653" src="https://assets.tumblr.com/assets/html/like_iframe.html?_v=5716f9145cbbcc5e21aa13229de5d4ed#name=wisdomsprydethemetestblog&post_id=160506016653&color=black&rk=4ktb4Bma&root_id=159609010143" scrolling="no" width="20" height="20" frameborder="0" class="like_toggle" allowtransparency="true" name="like_iframe_160506016653"></iframe></div></div> </td><td><div id="postreblog">Reblog</div> </td><td><div class="postnote"> Notes</div> </td><td><div class="postfrom">From</div> </td><td><div class="postsource"> Orig-Poster</div> </td><td><div class="postdatebutton"><button onclick="myFunction1(this)">Date</button></div></td><td><div class="posttagbutton"><button onclick="myFunction2(this)">Tags</button></div></td></tr></tbody></table><div class="postdate" style="display:none;"><p>05-10 1:52</p></div><div class="posttag" style="display:none;"><div class="tags"><p># Test text post# tags tags tags</p></div></div>
</div>
I am creating a game with jquery, the meaning of the game is that you should , with one element ( a bucket in this case "#spelare" ) catch other elements ".food" that are falling down from above. How can i make so that when the falling elements touch the (bucket), they disappear, and you get 1 score?
Thanks in advance for all help i can get!
Here is the code I have atm:
body{
text-align: center;
background-color:black;
}
#spelplan{
width: 1000px;
height:610px;
position:absolute;
margin-left:460px;
box-shadow: inset 0px 0px 50px;
background-color: green;
}
#spelare{
width:110px;
height: 12vh;
position: relative;
top:53.4vh;
background-image:url(hink.png);
background-size:cover;
}
.food{
width:50px;
height:50px;
position:absolute;
background-image:url(vattendroppe.png);
background-size:cover;
display:block;
}
p{
position:relative;
font-family: 'Electrolize', sans-serif;
}
#poäng{
color:white;
bottom:17vh;
right:45%;
}
#liv{
color:white;
bottom:18vh;
right:46.5%;
}
.fa-heart{
color:red;
bottom:21.5vh;
right:43.5%;
position:relative;
}
#info{
color:white;
font-family: 'Electrolize', sans-serif;
margin-top:68vh;
}
<!DOCTYPE html>
<html>
<head>
<title>Jquery Spel</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Electrolize" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode ==39 && $("#spelare").css("left") < '880px')
$("#spelare").animate({left: '+=20px'}, 0);
else if (e.keyCode ==37 && $("#spelare").css("left") > '0px')
$("#spelare").animate({left: '-=20px'}, 0);
});
setInterval(spawnFood,2000);
setInterval(fall, 0);
});
function spawnFood(){
var spelplanWidth = $('#spelplan').width();
var randPosX = Math.floor((Math.random()*spelplanWidth));
var element = $("<div class='food'></div>").css('left',randPosX).css('bottom', '446px');
$("#spelplan").append(element);
}
function fall(){
var elementFall = $(".food").animate({top: '+=20px'}, 500);
$("#spelplan").append(elementFall);
}
</script>
</head>
<body>
<h2 style="color:white">JQUERY SPEL</h2>
<div id="spelplan">
<div id="spelare"> </div>
<div class="food"> </div>
<p id="poäng"> Poäng: </p>
<p id="liv"> Liv: </p>
<i class="fa fa-heart" aria-hidden="true"></i>
</div>
<div id="info">
<h1> Instruktioner: </h1>
<p> Spelet går ut på att du med hjälp av hinken och piltangenterna ska fånga alla vattendroppar! <br/> Du måste hålla ut i 40 sekunder, missa tre vattendroppar så förlorar du! </p>
</div>
</body>
</html>
You have to constently compare each falling element position versus the bucket position.
A nice place for it is in your fall() function.
Have a look!
CodePen
$(document).ready(function(){
var score=0;
var fails=0;
//Bucket movement
$(document).keydown(function(e){
//console.log(e.which);
// if left or right keyboard arrow
if (e.keyCode ==39 && $("#spelare").css("left") < '880px')
$("#spelare").animate({left: '+=20px'}, 0);
else if (e.keyCode ==37 && $("#spelare").css("left") > '0px')
$("#spelare").animate({left: '-=20px'}, 0);
});
// Game init
var spanfoodInterval = setInterval(spawnFood,2000);
var fallInterval = setInterval(fall, 0);
// Water append
function spawnFood(){
var spelplanWidth = $('#spelplan').width();
var randPosX = Math.floor((Math.random()*spelplanWidth));
var element = $("<div class='food'></div>").css('left',randPosX).css('bottom', '446px');
$("#spelplan").append(element);
}
// dropping object animation
function fall(){
var elementFall = $(".food").animate({top: '+=20px'}, 500);
//$("#spelplan").append(elementFall);
$(".food").each(function(){
if( typeof($(this)) !="undefined" && typeof($("#spelare"))!="undefined" ){
// item position
var thisPosition = $(this).position();
var thisWidth = $(this).width();
// Bucket position and width
var bucketPosition = $("#spelare").position();
var bucketWidth = $("#spelare").width();
var bucketHeight = $("#spelare").height();
// If object and bucket at same position
if( thisPosition.top >= bucketPosition.top
&& thisPosition.left >= bucketPosition.left
&& thisPosition.left <= bucketPosition.left + bucketWidth ){
$(this).remove();
score++;
//console.log(score);
// Update the score display
$("#score").html(score);
}
// Food not catched...
if( thisPosition.top >= bucketPosition.top + bucketHeight){
$(this).remove();
fails++;
//console.log("FAILS: "+fails);
}
// if more than 3 miss => Game over.
if(fails>3){
$("#failMsg").show();
$("#spelare").remove();
$(".food").remove();
clearInterval(spanfoodInterval);
clearInterval(fallInterval);
}
}
});
}
}); // ready
body{
text-align: center;
background-color:black;
}
#spelplan{
width: 1000px;
height:610px;
position:absolute;
margin-left:460px;
box-shadow: inset 0px 0px 50px;
background-color: green;
}
#spelare{
width:110px;
height: 12vh;
position: relative;
top:53.4vh;
background-image:url(https://placehold.it/350x150); /* hink.png); */
background-size:cover;
}
.food{
width:50px;
height:50px;
position:absolute;
background-image:url(https://placehold.it/350x150); /* vattendroppe.png); */
background-size:cover;
display:block;
}
p{
position:relative;
font-family: 'Electrolize', sans-serif;
}
#failMsg{
position:fixed;
top:50%;
left:50%;
transform:translate(50% 50%);
color:white;
font-size:4em;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Electrolize" rel="stylesheet">
<h2 style="color:white">jQuery GAMES - Your score: <span id="score">0</span></h2><!-- JQUERY SPEL</h2-->
<div id="spelplan">
<div id="spelare"> </div>
<div class="food"> </div>
<p id="poäng"> Poäng: </p>
<p id="liv"> Liv: </p>
<i class="fa fa-heart" aria-hidden="true"></i>
</div>
<div id="info">
<h1> Instructions: </h1>
<p> The game is that you are using the bucket and the arrow keys to catch all the drops of water! <br/> You have to hold out for 40 seconds, missing three water drops, you lose! </p>
</div>
<div id="failMsg">Game over!</div>
Im new to this but I've been having some trouble with trying to get my timer and score values back to 0 before a new game of memory starts. The values do reset, but don't show it until that value is affected. For example, the value for the number of matches never goes back to 0, it stays on 10(the max number of pairs) until you find the first match of the next game where it will then turn to 1. Does anybody know how to get the values to show 0 again when a new board is called up instead of just resetting when that value is affected?
I have already set
var turns = 0
var matches = 0
and called in them up as 0 in the function newBoard().
My timer code is:
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
Where I have called up the resetTime() function in the function newBoard().
My full code is:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
matches = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>
Both of the variables you are settings are displayed in HTML span objects.
What seems to be happening is that when you reset the Javascript variable, the value is being changed, but the span object where it is displayed to the user is being left at its previous value until it needs to be updated again.
As far as I can tell, your objects have the ids: matchNumber and Count for the match and turn variables respectively. If this is the case, try changing your code to reset the values to zero in the HTML when the variables are reset to zero.
For example:
// Reset the Javascript Count
var turns = 0
// Reset the HTML object
document.getElementById('Count').innerHTML = 0;
// Reset the Javascript Match Count
var matches = 0
// Reset the HTML object
document.getElementById('matchNumber').innerHTML = 0;
If I failed to explain this well, please comment and I'll try to clarify further.
I am not 100% sure, but you can try replacing your function with this one:
function timedCount() {
if(c>10){
//flipBack();
resetTime();
return;
}
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}