Progress Bar(Javascript) - javascript

I want the progress bar working. On each input(First Name, Last Name, Full Name, Type your password, Retype your password), the progress should go from 0% to 20%, 40%, 60%, 80%, 100%. if a input field is blank, for each input it will not add 20% from the progress-bar. You can see the progress-bar at top of the web page.
*{margin:0; padding:0;}
#Black{
width:100%;
height:100%;
background:black;
color:white;
position:fixed;
}
#White{
width:600px;
height:auto;
background:rgba(255,255,255,0.1);
color:white;
margin:100px auto;
}
#Prog{
width:100%;
height:20px;
background:rgba(255,255,255,0.1);
color:white;
}
#Pro{
width:0%;
height:20px;
background:linear-gradient(to bottom, rgba(33,150,243,1) 50%, rgba(33,150,243,0.9) 50%);
}
#FirstName::selection, #LastName::selection, #FullName::selection, #PSW::selection, #MPSW::selection{
background:white;
color:black;
}
#FirstName, #LastName, #FullName, #PSW, #MPSW{
width:400px;
height:auto;
padding:20px;
background:black;
color:white;
outline:none;
margin:20px 80px;
border:2px solid white;
}
#FirstName::placeholder, #LastName::placeholder, #FullName::placeholder, #PSW::placeholder, #MPSW::placeholder{
user-select:none;
}
#Register{
width:200px;
height:auto;
padding:20px;
background:black;
color:white;
outline:none;
border:2px solid white;
margin-left:200px;
margin-bottom:20px;
cursor:pointer;
}
#Register:hover{
background:linear-gradient(to bottom, rgba(33,155,243,1) 50%, rgba(33,155,243,0.9) 50%);
color:white;
border:2px solid white;
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<body>
<div id="Black">
<div id="Prog">
<div id="Pro">0%</div>
</div>
<div id="White">
<form action="http://www.freelancer.com" method="POST">
<input type="text" placeholder=" First Name" id="FirstName"/>
<input type="text" placeholder=" Last Name" id="LastName"/>
<input type="text" placeholder=" Full Name" id="FullName"/>
<input type="text" placeholder=" Type your password" id="PSW"/>
<input type="text" placeholder=" Retype your password" id="MPSW"/>
<input type="submit" value="Register" id="Register"/>
</form>
</div>
<script>
var prog=document.getElementById("Prog");
var pro=document.getElementById("Pro");
var fname=document.getElementById("FirstName");
var lname=document.getElementById("LastName");
var full=document.getElementById("FullName");
var psw0=document.getElementById("PSW");
var mpsw0=document.getElementById("MPSW");
var firstname=document.getElementById("FirstName").value;
var lastname=document.getElementById("LastName").value;
var fullname=document.getElementById("FullName").value;
var psw=document.getElementById("PSW").value;
var mpsw=document.getElementById("MPSW").value;
document.getElementById("FirstName").value="";
document.getElementById("LastName").value="";
document.getElementById("FullName").value="";
document.getElementById("PSW").value="";
document.getElementById("MPSW").value="";
var width=0;
var i;
</script>
</div>
</body>
</html>
Thanks

You can add an event listener for the keypress event of each of the inputs to increase the progress by 20% (keypress is only fired when a character is outputted).
You can also add an event listener for the keydown event of each of the inputs and check if the keyCode is 8 (backspace) and if the current length of the value of the input is 1 (in which case that character will be deleted) to remove 20% from the progress.
JSFiddle: http://jsfiddle.net/p0kg4sb9/13/embedded/result
*{margin:0; padding:0;}
body{
overflow-y: auto;
}
#Black{
width:100%;
height:100%;
background:black;
color:white;
position:fixed;
}
#White{
width:600px;
height:auto;
background:rgba(255,255,255,0.1);
color:white;
margin:100px auto;
}
#Prog{
width:100%;
height:20px;
background:rgba(255,255,255,0.1);
color:white;
}
#Pro{
width:0%;
height:20px;
background:linear-gradient(to bottom, rgba(33,150,243,1) 50%, rgba(33,150,243,0.9) 50%);
}
#FirstName::selection, #LastName::selection, #FullName::selection, #PSW::selection, #MPSW::selection{
background:white;
color:black;
}
#FirstName, #LastName, #FullName, #PSW, #MPSW{
width:400px;
height:auto;
padding:20px;
background:black;
color:white;
outline:none;
margin:20px 80px;
border:2px solid white;
}
#FirstName::placeholder, #LastName::placeholder, #FullName::placeholder, #PSW::placeholder, #MPSW::placeholder{
user-select:none;
}
#Register{
width:200px;
height:auto;
padding:20px;
background:black;
color:white;
outline:none;
border:2px solid white;
margin-left:200px;
margin-bottom:20px;
cursor:pointer;
}
#Register:hover{
background:linear-gradient(to bottom, rgba(33,155,243,1) 50%, rgba(33,155,243,0.9) 50%);
color:white;
border:2px solid white;
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css"/>
<body>
<div id="Black">
<div id="Prog">
<div id="Pro">0%</div>
</div>
<div id="White">
<form action="http://www.freelancer.com" method="POST">
<input type="text" placeholder=" First Name" id="FirstName"/>
<input type="text" placeholder=" Last Name" id="LastName"/>
<input type="text" placeholder=" Full Name" id="FullName"/>
<input type="text" placeholder=" Type your password" id="PSW"/>
<input type="text" placeholder=" Retype your password" id="MPSW"/>
<input type="submit" value="Register" id="Register"/>
</form>
</div>
<script>
var prog=document.getElementById("Prog");
var pro=document.getElementById("Pro");
var progress = 0;
var firstNameInputted = false;
var lastNameInputted = false;
var fullNameInputted = false;
var pswInputted = false;
var mpswInputted = false;
var firstName = document.getElementById("FirstName");
firstName.addEventListener("keypress", function(e){
if(!firstNameInputted){
firstNameInputted = true;
progress += 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
firstName.addEventListener("keydown", function(e){
if(e.keyCode == 8&&firstName.value.length==1){
firstNameInputted = false;
progress -= 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
var lastName = document.getElementById("LastName");
lastName.addEventListener("keypress", function(e){
if(!lastNameInputted){
lastNameInputted = true;
progress += 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
lastName.addEventListener("keydown", function(e){
if(e.keyCode==8&&lastName.value.length==1){
lastNameInputted = false;
progress -= 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
var fullName = document.getElementById("FullName");
fullName.addEventListener("keypress", function(e){
if(!fullNameInputted){
fullNameInputted = true;
progress += 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
fullName.addEventListener("keydown", function(e){
if(e.keyCode==8&&fullName.value.length==1){
fullNameInputted = false;
progress -= 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
var psw = document.getElementById("PSW");
psw.addEventListener("keypress", function(e){
if(!pswInputted){
pswInputted = true;
progress += 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
psw.addEventListener("keydown", function(e){
if(e.keyCode==8&&psw.value.length==1){
pswInputted = false;
progress -= 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
var mpsw = document.getElementById("MPSW");
mpsw.addEventListener("keypress", function(e){
if(!mpswInputted){
mpswInputted = true;
progress += 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
mpsw.addEventListener("keydown", function(e){
if(e.keyCode==8&&mpsw.value.length==1){
mpswInputted = false;
progress -= 20;
pro.textContent = progress + "%";
pro.style.width = progress + "%";
}
});
</script>
</div>
</body>
</html>

Related

Need help in drag and drop uploading

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);
?>

html graphic upload won't work on firefox

So I've been working on a HTML form for graphical upload and it turned out to be more confusing that i originally thought. The code i have written works on Chromium 62.0.3202.94, however on Firefox 57.0 the percentage stays at 0% and won't change. Does anyone have any idea why this might be happening? here's the code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>File upload with progress</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById("fileToUpload").files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById("fileName").innerHTML = "Name: " + file.name;
document.getElementById("fileSize").innerHTML = "Size: " + fileSize;
document.getElementById("fileType").innerHTML = "Type: " + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", "upload.php");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById("percent").innerHTML = percentComplete.toString() + "%";
}
else {
document.getElementById("percent").innerHTML = "unable to compute";
}
}
</script>
</head>
<body>
<h1>File upload with progress bar</h1>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="myFile" id="fileToUpload" onchange="fileSelected();">
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="submit" onclick="uploadFile()" value="Upload">
</div>
<div class="progress">
<div class="bar"></div>
<div class="percent" id="percent">0%</div>
</div>
</form>
</body>
</html>
There is one big issue with the code - browsers default submit action is not prevented.
Prevented by:
Removing un-needed attributes from <form>
Removing the onclick handler from the <submit>. Using <form onsubmit instead.
<form onsubmit handler (uploadFile) returns false.
After cleaning that up in the code, after that worked in Chrome 62.0.3202.94 and Firefox 57.0, IE 11.
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>File upload with progress</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById("fileToUpload").files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById("fileName").innerHTML = "Name: " + file.name;
document.getElementById("fileSize").innerHTML = "Size: " + fileSize;
document.getElementById("fileType").innerHTML = "Type: " + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", "upload.php");
xhr.send(fd);
return false; // Prevent browser default submit action
}
function uploadProgress(evt) {
console.log("uploadProgress", evt);
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById("percent").innerHTML = percentComplete.toString() + "%";
}
else {
document.getElementById("percent").innerHTML = "unable to compute";
}
}
</script>
</head>
<body>
<h1>File upload with progress bar</h1>
<form onsubmit="return uploadFile()">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="myFile" id="fileToUpload" onchange="fileSelected();">
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="submit" value="Upload">
</div>
<div class="progress">
<div class="bar"></div>
<div class="percent" id="percent">0%</div>
</div>
</form>
</body>
</html>

JQuery game, element disappear when in contact with another element issue

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>

Expanding search bar not expanding before search

There are 2 problems when running this search.
1: When clicking the magnifier, instead of just opening the search bar, it searches immediately. 2: if more than 2 characters are typed and then the search bar is closed (by click off it) then reopened (by clicking back on it) the search button and search text doesn't align properly. https://jsfiddle.net/mkLj7dap/
HTML:
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<meta charset="UTF-8">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<div class=" top-search">
<div class="ty-search-block">
<form action="www.example.com/" name="search_form" method="get" class="cm-processed-form">
<input type="hidden" name="subcats" value="Y">
<input type="hidden" name="pcode_from_q" value="Y">
<input type="hidden" name="pshort" value="Y">
<input type="hidden" name="pfull" value="Y">
<input type="hidden" name="pname" value="Y">
<input type="hidden" name="pkeywords" value="Y">
<input type="hidden" name="search_performed" value="Y">
<input type="text" name="hint_q" value="" id="search_input" title="" class="ty-search-block__input cm-hint"><button title="" class="ty-search-magnifier" type="submit"><i class="material-icons">search</i></button>
<input type="hidden" name="dispatch" value="products.search">
</form>
</div>
</div>
</body>
</html>
CSS:
.cm-processed-form{
position:relative;
min-width:50px;
width:0%;
height:50px;
float:right;
overflow:hidden;
-webkit-transition: width 0.1s;
-moz-transition: width 0.1s;
-ms-transition: width 0.1s;
-o-transition: width 0.1s;
transition: width 0.1s;
}
.ty-search-block__input{
top:0;
right:0;
border:0;
outline:0;
background:#dcddd8;
width:100%;
height:50px;
margin:0;
padding:0px 55px 0px 20px;
font-size:20px;
color:red;
}
.ty-search-block__input::-webkit-input-placeholder {
color: #d74b4b;
}
.ty-search-block__input:-moz-placeholder {
color: #d74b4b;
}
.ty-search-block__input::-moz-placeholder {
color: #d74b4b;
}
.ty-search-block__input:-ms-input-placeholder {
color: #d74b4b;
}
.ty-search-magnifier{
width:50px;
height:50px;
display:block;
position:absolute;
top:0;
font-family:verdana;
font-size:22px;
right:0;
padding-top:10px;
margin:0;
border:0;
outline:0;
line-height:30px;
text-align:center;
cursor:pointer;
color:#dcddd8;
background:#172b3c;
}
.cm-processed-form-open{
width:100%;
}
JS:
$(document).ready(function(){
var submitIcon = $('.ty-search-magnifier');
var inputBox = $('.ty-search-block__input');
var searchBox = $('.cm-processed-form');
var isOpen = false;
submitIcon.click(function(){
if(isOpen == false){
searchBox.addClass('cm-processed-form-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('cm-processed-form-open');
inputBox.focusout();
isOpen = false;
}
});
submitIcon.mouseup(function(){
return false;
});
searchBox.mouseup(function(){
return false;
});
$(document).mouseup(function(){
if(isOpen == true){
$('.ty-search-magnifier').css('display','block');
submitIcon.click();
}
});
});
function buttonUp(){
var inputVal = $('.ty-search-block__input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.ty-search-magnifier').css('display','none');
} else {
$('.ty-search-block__input').val('');
$('.ty-search-magnifier').css('display','block');
}
}
Change the script as bellow to prevent the default click event, when search box not expanded:
submitIcon.click(function (event) {
if (isOpen == false) {
event.preventDefault();
searchBox.addClass('cm-processed-form-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('cm-processed-form-open');
inputBox.focusout();
isOpen = false;
}
});

Adding a centered "loading..." message inside the progress bar

How can the code below be modified such that I would be able to add a centered "loading..." message inside the box while the progress bar runs in the background? Ie. it would display LOADING..." in the center of the box while the progress bar runs in the background inside the DIV.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
var progress_run_id = null;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
clearInterval( progress_run_id );
w = 0;
alert("done")
} else {
w = parseInt(w) + 5 + 'px';
}
node.style.width = w;
}
function runit() {
progress_run_id = setInterval(progress, 30);
}
</script>
</head>
<body>
<div style="border: 1px solid #808080; width:200px; height:20px;">
<div id="progress" style="height:20px; width:0px; background-color:#DBDBDB;"/>
</div>
</div>
<p>Start</p>
</body>
</html>
<div style="border: 1px solid #808080; width:200px; height:20px;">
<div id="progress" style="text-align: center; height:20px; width:0px; background-color:#DBDBDB;"/>
<div style=" position: fixed; left: 92px ">loading</div>
</div>
</div>

Categories

Resources