Fill a circle over time - javascript

I am doing a project where I created a countdown timer using JavaScript. It features stop-, start-, and reset buttons.
I want to create a fill effect animation starting from the bottom, based on the countdown timer. I want the fill effect to fill a certain percentage of the circle so that when the countdown reaches 0, the whole circle will be filled.
I want to use vanilla JavaScript. No jQuery or SVG.
Here is my code so far for the basic timer starting with HTML, then CSS and my Javascript code.
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<h1>Pomodoro Clock</h1>
<div class="container">
<div class="row">
<h3>Session Length</h3>
<div class="row button1">
<button type="button" onclick="decreaseTime()">-</button>
<span id="SessionLength">25</span>
<button type="button" onclick="increaseTime()">+</button>
</div>
</div>
<!--My Start/Stop/Reset buttons-->
<div class="row">
<div class="myButtons">
<button type="button" onclick="startTime()">Start</button>
<button type="button" onclick="stopTime()">Stop</button>
<button type="button" onclick="resetTime()">Reset</button>
</div>
</div>
<!--My Circle-->
<div class="row">
<div class="circleDraw">
<h2 class="text-center">Session</h2>
<h1 id="output">25:00</h1>
</div>
</div>
</div>
h1{
text-align: center;
}
h3{
text-align: right;
padding-right: 30%;
}
.myButtons{
text-align: center;
padding-top: 10%;
}
.circleDraw{
border-radius: 50%;
border: 2px solid;
width: 300px;
height: 300px;
margin: 50px auto;
}
.text-center{
text-align: center;
padding: 30px;
}
.txt-center{
text-align: center;
}
.button1{
text-align: right;
padding-right: 35%
}
var time = 1500;
var running = 0;
var myStopID;
var startTime = function(){
running = 1;
if(running == 1){
timer();
}
}
var stopTime = function(){
clearTimeout(myStopID);
running = 0;
}
var resetTime = function(){
if(running == 0){
time = 1500;
}
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById('output').innerHTML= min;
document.getElementById('SessionLength').innerHTML= min;
}
var timer = function(){
if(running == 1){
myStopID = setTimeout(function(){
time--;
var min = Math.floor(time / 60);
var sec = time % 60;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
document.getElementById("output").innerHTML= min + ":" + sec;
timer();
}, 1000);
}
}
function decreaseTime(){
if(time <= 0){
return 0;
}
time = time - 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}
function increaseTime(){
if(time >= 5940){
return 5940;
}
time = time + 60;
var min = Math.floor(time/60);
document.getElementById('SessionLength').innerHTML= min;
document.getElementById('output').innerHTML= min;
}

What you have done so far looks good. I'd look at using the canvas element and the arc() method on that to draw the circle and partial fill.
More info here...
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
And basic Canvas and SVG example for drawing a circle in this answer...
https://stackoverflow.com/a/6936351/4322803

Related

Score not incrementing

I am programming a simple game in javascript and when the user hovers on the given coordinates it's score increases. My problem is the score does not increment after 1.
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
//Generating Co-ordinates
function generate() {
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
function points(x, y) {
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
points(x, y);
}
})
Even after adding a global count variable, your code is not working properly because of your if (xco == x && yco == y) condition fails after first run. Here you are comparing randomly generated x and y with xco, yco and updating score and calling generate again.
On your generate function you are creating new local variable x and y, not updating the global x and y. And the subsequent comparison (xco == x && yco == y) will fail because it still using the old x and y.
On your generate function, updating the global x and y should fix this issue,
x = Math.floor(Math.random() * 500) + 150;
y = Math.floor(Math.random() * 500) + 150;
Here is the complete code, I also made some minor changes, removed some redundant and duplicate codes
// Code goes here
$(document).ready(function(){
//on clicking let's play
var t = 120;
var count = 0;
$("button.play").click(function(event){
event.preventDefault();
$(".fadeout").fadeOut(2000, function(){
$(".heading").text("Click on the Start button when you're ready");
});
$(".hidden").attr("hidden", false);
});
function start(){
//init game timer
var Timer = setInterval(function(){
document.getElementById("time1").innerHTML = t;
--t;
if(t < 0){
clearInterval(Timer);
document.getElementById("timeout").innerHTML = "Time's Up |";
$("div.frame").attr("hidden",true);
}
},1000);
var x = Math.floor(Math.random()*500)+150;
var y = Math.floor(Math.random()*500)+150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function(event){
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
points(xco, yco);
})
$("div.frame").mouseout(function(event){
document.getElementById("display1").innerHTML = " ";
document.getElementById("display2").innerHTML = " ";
})
//Generating Co-ordinates
function generate(){
x = Math.floor(Math.random()*500) + 150;
y = Math.floor(Math.random()*500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
}
function points(xco, yco){
if(x == xco && y == yco){
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
}
$("button.start").click(function(event){
event.preventDefault();
start();
$(this).fadeOut(1500);
$(this).attr("disabled",true);
$(".afterstart").fadeOut(1500);
});
});
/* Styles go here */
body{
height: 1200px;
background-size: cover;
}
.jumbotron{
margin-top: 250px;
padding: 20px;
height: 350px;
background-size: cover;
background-attachment: fixed;
}
.heading{
font-size: 30px;
margin-top: 100px;
}
.frame{
height: 1000px;
width: 1500px;
border: 10px solid black;
}
ul {
background: #40475A;
padding: 10px;
width: 100%;
}
.stats{
font-size: 30px;
margin-top: 80px;
}
.info{
font-size: 30px;
color:aliceblue;
}
.bold{
font-size: 25px;
color:antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Irritate</title>
</head>
<body>
<div>
<ul class="nav nav-pills pl-5 fixed-top d-flex justify-content-center" style="font-size: 25px">
<li class="nav-item">
<a class="nav-link" data-toggle="pill" id="display1"></a>
</li>
<li class="nav-item">
<a class="nav-link" id="display2"></a>
</li>
</ul>
</div>
<div class="jumbotron fadeout">
<div class="display-3 text-muted d-flex justify-content-center"> Hand-Job </div>
<p class="info"> All you have to do is try to match the co-ordinates that will display on the screen </p>
<p class="bold"><kbd>PS:</kbd>This game will test your patience</p>
<form>
<div class="input-group w-75">
<div class="input-group-prepend">
<span class="input-group-text">Name:</span>
</div>
<input type="text" class="form-control" value="">
<div class="input-group-append">
<button class="btn btn-outline-success play">Let's Play</button>
</div>
</div>
</form>
</div>
<div class="hidden" hidden="true">
<div>
<p class="text-danger heading afterstart"></p>
<button class="btn btn-danger w-25 start">Start</button>
<div class="d-flex d-flex-inline stats">
<p class="ml-3">X Co-ordinate:<span id="demo1" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Y Co-ordinate:<span id="demo2" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Time Left:<span id="time1" class="ml-2"></span> <span> | </span></p>
<p id="timeout" class="ml-3"></p>
<p>Score: <span id="score"></span></p>
</div>
</div>
<div class="frame ml-2">
</div>
<p id="result"></p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
Here is plunker url for the above code https://plnkr.co/edit/7ia7MkMimzlsAxTCWAc9?p=preview
i think its because your count variable is local and only live in if block if you want to have count in other place please declare it as global variable
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
var count = 0;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
...
})

Repeat script through multiple elements

I have created a script that converts the HTML value from an element into a percentage, the percentage value then determines the width of another element (in this case a bar).
This is all well and good for a single element (as you will see), however, does not work when I have an element echoing through a page. Can I be pointed in the right direction here?
Current JS Fiddle: http://jsfiddle.net/ctalke/27no66rm/
//==================================== Bar Percentage Start ================================//
var a = document.getElementsByClassName('term')[0].innerHTML;
var b = document.getElementsByClassName('age')[0].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
document.getElementsByClassName('barv')[0].style.width = Math.round(e) + '%';
document.getElementsByClassName('barv')[0].innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
var a1 = document.getElementById("barv");
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
//===================================== Bar Colour End ==================================//
.bar {
text-align: center;
height: 20px;
border: 1px solid black;
color: white;
}
.hide {
display: none;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
color: black!important;
}
.green {
background-color: green;
}
<!-- Term -->
<div class="term hide">36</div>
<!-- Age -->
<div class="age hide">35</div>
<!-- Progress Bar -->
<div class="bar barv red"></div>
<br>
<!-- Term 1 -->
<div class="term hide">36</div>
<!-- Age 1 -->
<div class="age hide">2</div>
<!-- Progress Bar 1 -->
<div class="bar barv yellow"></div>
<br>
<!-- Term 2 -->
<div class="term hide">36</div>
<!-- Age 2 -->
<div class="age hide">15</div>
<!-- Progress Bar 2 -->
<div class="bar barv green"></div>
You just need to iterate over the snippet using a for loop instead.
var bars = document.getElementsByClassName('bar');
for (i = 0; i < bars.length; i++) {
// Your code here
}
And replace [0] with [i]
//==================================== Bar Percentage Start ================================//
var bars = document.getElementsByClassName('bar');
for (i = 0; i < bars.length; i++) {
var a = document.getElementsByClassName('term')[i].innerHTML;
var b = document.getElementsByClassName('age')[i].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
document.getElementsByClassName('barv')[i].style.width = Math.round(e) + '%';
document.getElementsByClassName('barv')[i].innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
var a1 = document.getElementsByClassName("barv")[i];
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
}
//===================================== Bar Colour End ==================================//
.bar {
text-align: center;
height: 20px;
border: 1px solid black;
color: white;
}
.hide {
display: none;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
color: black!important;
}
.green {
background-color: green;
}
<!-- Term -->
<div class="term hide">36</div>
<!-- Age -->
<div class="age hide">35</div>
<!-- Progress Bar -->
<div class="bar barv red"></div>
<br>
<!-- Term 1 -->
<div class="term hide">36</div>
<!-- Age 1 -->
<div class="age hide">2</div>
<!-- Progress Bar 1 -->
<div class="bar barv yellow"></div>
<br>
<!-- Term 2 -->
<div class="term hide">36</div>
<!-- Age 2 -->
<div class="age hide">15</div>
<!-- Progress Bar 2 -->
<div class="bar barv green"></div>
You can reduce the repetition of same selectors by caching them in a variable instead.
//==================================== Bar Percentage Start ================================//
var bars = document.querySelectorAll('.bar');
for (i = 0; i < bars.length; i++) {
var bar = bars[i];
var term = document.querySelectorAll('.term')[i];
var age = document.querySelectorAll('.age')[i];
var a = term.innerHTML;
var b = age.innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
bar.style.width = Math.round(e) + '%';
bar.innerHTML = Math.round(e) + '%';
//==================================== Bar Percentage End =================================//
//===================================== Bar Colour Start ==================================//
if (e < 50) {
bar.classList.add("green");
} else if (e < 99) {
bar.classList.add("yellow");
} else {
bar.classList.add("red");
}
}
//===================================== Bar Colour End ==================================//
I might be misreading your question, but are you asking about looping through all of the elements? If you're trying to do something to more than 1 element, try something like this
const arrayOfElements1 = document.querySelectorAll('yourCSSselectorGoesHere');
const arrayOfElements2 = document.querySelectorAll('yourCSSselectorGoesHere');
for (let i = 0; i < arrayOfElements.length; i += 1) {
arrayOfElements1[i].doStuff;
}
In the doStuff above you can do arrayOfElements1[i].innerHTML / arrayOfElements2[i].innerHTML * 100. I'm not entirely clear on what you're needing so let me know if I've misunderstood.
Just put your code in a for loop.
var barvs = document.getElementsByClassName("barv");
for (var index=0; index<barvs.length ;index++) {
var a = document.getElementsByClassName('term')[index].innerHTML;
var b = document.getElementsByClassName('age')[index].innerHTML;
var c = 100;
var d = b / a;
var e = d * c;
barvs[index].style.width = Math.round(e) + '%';
barvs[index].innerHTML = Math.round(e) + '%';
var a1 = barvs[index];
if (e < 50) {
a1.className += " green";
} else if (e < 99) {
a1.className += " yellow";
} else {
a1.className += " red";
}
}

jquery : Text on moving div (infinite wall)

I need to make an infinite wall which will pull text from database and show it on the wall. I have written this code -
$(function() {
var x = 0;
var y = 100.0;
var z=0;
setInterval(function() {
x -= 0.1;
y -= 0.1;
z++;
if (x <= -100.0){
$("#h1d1").html("loop div 1 :" + z);
x = 0;
}
if (y <= 0){
$("#h1d2").html("loop div 2 :" + z);
y = 100.0;
}
$('#movimg1').css('left', x + "%");
$('#movimg2').css('left', y + "%");
}, 10);
$("#stopbutton").click(function() {
$('#movimg1').stop();
});
})
But the text are not behaving as I wanted it to behave. It changes in the middle of the screen which I don't want. I need the text to change when it is out of view.
https://jsfiddle.net/oa0wdxcx/2/
A couple more things- I want to add a play/pause button. Any advice on how I could achieve that would be much appreciated. Also I want the divs to be inside #wrap div, but if I change the position attribute to relative, the divs don't remain together.
Thanks in advance.
The problem was in the conditions.
if (x <= -100.0) {
z++;
$("#h1d1").html("loop div 1 :" + z);
x = 100; /* change this line */
}
if (y <= -100.0) { /* change this line */
w++;
$("#h1d2").html("loop div 2 :" + w);
y = 100;
}
the conditions says that if any of these two divs reaches left:-100% then the element must place at the end of queue at left:100%.
And one other thing you can combine these if statements and only use x to do the transition.
For start and stop button to work, you should kill the simulation to stop by using clearInterval() function, and call doSimulate() to start again:
var started = true;
$("#stopbutton").click(function () {
if(started) {
clearInterval(sim);
$(this).html('Start');
started = false;
}else{
doSimulate();
$(this).html('Stop');
started = true;
}
});
Here is jsFiddle With Start/Stop Working.
Look at this JSFiddle, i added one more to get a smooth transition back to start.. The third should contain same message as first.
HTML
<body>
<div class="row">
<div class="col-xs-1"></div>
<div id="wrap" class="col-xs-10">
<div class="movimg message1" id="movimg1">
<h1 class="header">start div 1</h1>
</div>
<div class="movimg message2" id="movimg2">
<h1 class="header">start div 2</h2>
</div>
<div class="movimg message1" id="movimg3">
<h1 class="header">start div 1</h1>
</div>
</div>
<div class="col-xs-1"></div>
</div>
<div class="row">
<button class="button" id="startbutton" style="display:none;">Start</button>
<button class="button" id="stopbutton">Stop</button>
</div>
</body>
JavaScript
$(function () {
var x = 200.0;
var interval;
function start(){
interval = setInterval(function () {
x -= 0.1;
if (x <= 0.0) {
x = 200;
}
$('#movimg1').css('left', (x-200) + "%");
$('#movimg2').css('left', (x-100) + "%");
$('#movimg3').css('left', x + "%");
}, 10);
}
start();
$("#stopbutton").click(function () {
window.clearInterval(interval);
$(this).hide();
$("#startbutton").show();
});
$("#startbutton").click(function () {
start();
$(this).hide();
$("#stopbutton").show();
});
})
CSS
body {
overflow: hidden;
}
#wrap {
width: 80%;
left: 10%;
}
.movimg{
position: absolute;
height: 600px;
width: 100%;
background-image: url('https://s-media-cache-ak0.pinimg.com/736x/89/ed/e5/89ede56bcc8243787e55676ab28f287f.jpg');
}
#movimg1 {
left: 0%;
}
#movimg2 {
left: 100%;
}
#movimg3 {
left: 200%;
}
.header {
text-align: center;
}
.button{
top: 600px;
position: relative;
}
UPDATE
Now with Stop and Start buttons: JSFiddle

Why is my webpage components loading slow?

Here is my webpage with a puzzle game I am making:
http://www.acsu.buffalo.edu/~jamesber/GameOne.html#
If you take a look at it, keep refreshing the page, it takes a second or two for all the components to load.
I thought it was that the ajax was loading slow but I don't think that is it. Someone please help! Thanks!
My javascript code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes /smoothness/jquery-ui.css" />
<style>
#puzzle {
width: 450px;
height: 450px;
outline: 4px solid black;
padding: 0px;
-webkit-padding-start: 0px;
margin-left:440px;
margin-right:auto;
margin-top:-205px;
}
.helper {
width: 200px;
height: 200px;
border: 1px solid black;
margin: 0px;
}
.piece {
float: left;
display: block;
width: 148px;
height: 148px;
border: 1px solid black;
margin: 0px;
background-size: 450px 450px;
background-repeat:no-repeat;
}
.piece span {
display:inline-block;
border:1px solid #FFFFFF;
color: #B80000;
display: none;
}
.ui-dialog .ui-dialog-title {
text-align: center;
width: 100%;
}
</style>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var plant = "";
$.when($.ajax({"url":"http://botanicalapp.com/api/v1/plants/?photo=true"}))
.done(function(fullData){
(function(){
var rand = Math.floor(Math.random()*fullData.length)
plant = fullData[rand].plant.image_default.url;
})()
startGame();
});
function startGame() {
$("#puzzle div").css({'background-image':'url('+ plant +')'});
$("#helper").attr("src",plant);
var puzzle = $("#puzzle");
var pieces = $("#puzzle div");
pieces.sort(function (a, b) {
var temp = parseInt(Math.random() * 100);
var isOddOrEven = temp % 2;
var isPosOrNeg = temp > 5 ? 1 : -1;
return (isOddOrEven * isPosOrNeg);
}).appendTo(puzzle);
var checkDone = false;
var timer;
var secs = 0;
var mins = 0;
var millsecs = 0;
var timeString = document.getElementById("time");
timeString.innerHTML = "00:00:00";
function update(){
if(millsecs > 98) {
secs++;
millsecs = 0;
if(secs > 59){
mins++;
secs = 0;
}
}
else {
millsecs++;
}
if((millsecs<10) && (secs<10) && (mins<10)) {
timeString.innerHTML = '0' + mins + ':0' + secs + ':0' + millsecs;
}
else if ((millsecs<10) && (secs<10)) {
timeString.innerHTML = mins + ':0' + secs + ':0' + millsecs;
}
else if ((millsecs<10) && (mins<10)) {
timeString.innerHTML = '0' + mins + ':' + secs + ':0' + millsecs;
}
else if((secs<10) && (mins<10)){
timeString.innerHTML = '0' + mins + ':0' + secs + ':' + millsecs;
}
else if (millsecs<10) {
timeString.innerHTML = mins + ':' + secs + ':0' + millsecs;
}
else if (secs<10){
timeString.innerHTML = mins + ':0' + secs + ':' + millsecs;
}
else if (mins<10) {
timeString.innerHTML = '0' + mins + ':' + secs + ':' + millsecs;
}
else {
timeString.innerHTML = mins + ':' + secs + ':' + millsecs;
}
}
function start(){
timer = setInterval(function() {update()}, 10);
}
document.getElementById("instr").onclick=function(){ $("#instruct").dialog("open"); };
start();
initSwap();
$("#final").dialog({
autoOpen: false,
modal: true,
width: 900,
resizable: false,
height: 540,
position: [250,75],
dialogClass: "fixed-dialog",
title: "Congratulations Puzzle Solved!",
draggable: false
});
$("#instruct").dialog({
autoOpen: false,
modal: true,
width: 700,
resizable: false,
height: 250,
position: [325,75],
dialogClass: "fixed-dialog",
draggable: false,
title: "Puzzle Instructions",
open: function(ev, ui) { clearTimeout(timer); },
close: function(ev, ui) { if (!checkDone) { start(); } }
});
function initSwap() {
initDroppable($("#puzzle div"));
initDraggable($("#puzzle div"));
}
function initDraggable($elements) {
$elements.draggable({
appendTo: "body",
helper: "clone",
cursor: "move",
revert: "invalid"
});
}
function initDroppable($elements) {
$elements.droppable({
activeClass: "ui-state-default",
hoverClass: "ui-drop-hover",
accept: ":not(.ui-sortable-helper)",
over: function (event, ui) {
var $this = $(this);
},
drop: function (event, ui) {
var $this = $(this);
var linew1 = $(this).after(ui.draggable.clone());
var linew2 = $(ui.draggable).after($(this).clone());
$(ui.draggable).remove();
$(this).remove();
initSwap();
var finished = "1,2,3,4,5,6,7,8,9";
var started = '';
$("#puzzle div").each(function(){
var image = $(this).attr("id");
started += image.replace("recordArr_","")+",";
});
started = started.substr(0,(started.length)-1);
if(started == finished){
checkDone = true;
clearTimeout(timer);
$("#thePlant").attr("src",plant);
$("#final").dialog("open");
}
}
});
}
}
});
</script>
</head>
<body>
<big><big><big><div id="time"></div></big></big></big>
<div id="help"><image id="helper" width="200", height="200"/></div>
<div id="final"><img id="thePlant" width="450", height="450" <p align="top"> Plant Information! </p></div>
<div id="instruct"><p> To begin playing a picture will appear that has been scrambled.
Your job is to drag each piece into the location you think it should be.
When you move all the pieces into their correct locations a window will appearthat will tell you
more about that plant and where to find it when you visit the Botanical Gardens.
If you need help, click on the hints button and numbers will appear in the corners
of the pictures to show you what order the pieces should be in. Good Luck!</p></div>
<div id="maindiv">
<div id="puzzle">
<div id="1" class="piece" style="background-position: -000px -000px;"><b><big><big><span>1</span></big></big></b></div>
<div id="6" class="piece" style="background-position: -301px -151px;"><b><big><big><span>6</span></big></b></big></div>
<div id="9" class="piece" style="background-position: -301px -301px;"><b><big><big><span>9</span></big></big></b></div>
<div id="4" class="piece" style="background-position: -000px -151px;"><b><big><big><span>4</span></big></big></b></div>
<div id="3" class="piece" style="background-position: -301px -000px;"><b><big><big><span>3</span></big></big></b></div>
<div id="7" class="piece" style="background-position: -000px -301px;"><b><big><big><span>7</span></big></big></b></div>
<div id="2" class="piece" style="background-position: -151px -000px;"><b><big><big><span>2</span></big></big></b></div>
<div id="5" class="piece" style="background-position: -151px -151px;"><b><big><big><span>5</span></big></big></b></div>
<div id="8" class="piece" style="background-position: -151px -301px;"><b><big><big><span>8</span></big></big></b></div>
</div>
</div>
Instructions
Toggle Hints
Use Firebug, you can see in the network tab which part is slow.
You should extract your javascript and css in seperate files, they can be compressed then.
As other users suggested - if you are loading 3rd party content from the internet, you have to keep in mind that download times may vary on each page refresh.
Anyway, my advice is to move your custom js code into separate file and minify it when you finish the development process.
And the most important: place that file just before </body> tag.
The reason for doing so is that scripts at the head of a page are blocking the browser. It must stop processing the website until all of the scripts are downloaded and parsed.
A great discussion about that matter is available on stackoverflow, you should go through it here.
A get-request for http://botanicalapp.com/api/v1/plants/?photo=true is taking around 2-3.5 seconds so you're probably not going to be able to process it faster than that.
I would advice you to move the script tag containing your sites javascript to the bottom of the page. It doesn't have to reside in head and putting it right before the closing tag of body allows other external component on the page to download as quickly as possible before the scripts are loaded.
Nothing seems to make it better. I was wondering. Is there a way to put like a smoother looking loading screen to cover it up? Was looking into a js spinner but couldn't get that to work right. But could this be done?

javascript to replace button text with images...trigger button with external event

I found this stopwatch javascript, complete with "Start", "Stop" and "Reset" buttons. The functionality of this script is great, but I would like to spruce it up a bit. I've managed to style the button background with CSS border-image, but I want to use javascript to replace the "Start", "Stop" and "Reset" text with icons.
I would also like to make the timer start when the user clicks on another area. For example, I may use this to track how long a user takes to solve a puzzle...so it would be great if the "Start" button could be activated upon the user's FIRST event recorded on the puzzle. I though about making an event listener for any click, but I'm afraid that may cause the button to toggle Start/Stop on each event.
Lastly, it would be nice if the "Stop" button triggered a hidden div with a message screen that shows up on top of the puzzle while the game is paused. Below is a snippet of my code
JAVASCRIPT
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
= min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop";}
if (text == "Stop") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
alert("Timer is Paused...Resume?");
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
CSS
.button {
border-width:0 5px; -webkit-border-image:url(../images/toolButton-791569.png) 0 5 0 5; padding:7px 0; font: bold 12px Arial,sans-serif; color:#fff; width:auto; margin:5px 10px 0 0; width:auto; height: 25px; text-align:center; cursor:pointer;
}
HTML
<div id="timer">
<form name="clock">
<input type="text" size="14" name="stwa" value="00 : 00 : 00" style="text-align:center; position: relative; top: 0px; background: #ccc; font-weight: bold; font-size: 14px;" />
<br/><input type="button" class="button" name="theButton" onClick="stopwatch(this.value);" value="Start" />
<input type="button" class="button" value="Reset" onClick="resetIt();reset();" />
</form></div>
I'm sure the brilliant programmers in this community might find this question to be trivial, but please forgive me. I am a novice programmer and this challenge is causing me many sleepless nights. Please help...
Thanks,
Carlos
Here you go http://jsfiddle.net/mplungjan/C4wjV/
I did not do the pause button
<style type="text/css">
img { height:50px }
#stwa {text-align:center; position: relative; top: 0px; background: #ccc; font-weight: bold; font-size: 14px;}
</style>
<script type="text/javascript">
var buttons = {
Start:"http://morethanvoice.net/m1/img/play.gif",
Stop:"http://morethanvoice.net/m1/img/pause.gif"
}
var sec = 0,min = 0,hour = 0,SD;
function stopwatch(text) {
sec++;
if (sec === 60) {
sec = 0;
min += 1;
}
if (min === 60) {
min = 0;
hour += 1;
}
document.clock.stwa.value = ((hour<10) ? "0"+hour : hour) + " : " +
((min<10) ? "0" + min : min) + " : " +
((sec<10)? "0" + sec:sec);
if (text) { // i.e. we are clicked
if (text==="Stop") window.clearTimeout(SD);
text = (text==="Start")?"Stop":"Start";
document.getElementById('stopstart').title=text;
document.getElementById('stopstarticon').src=buttons[text];
}
if (!text || text === "Stop") SD=window.setTimeout(function() {stopwatch()}, 1000);
return false;
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
document.getElementById('stopstart').title = "Start"
document.getElementById('stopstarticon').src=buttons["Start"];
window.clearTimeout(SD);
document.clock.stwa.value=document.clock.stwa.defaultValue;
return false;
}
</script>
<form name="clock"><input type="text" size="14" id="stwa" name="stwa" value="00 : 00 : 00" />
</form><br/>
<a href="#" id="stopstart" title="Start"
onClick="return stopwatch(this.title)"><img id="stopstarticon" src="http://morethanvoice.net/m1/img/play.gif" border="0" /></a>
<img src="http://morethanvoice.net/m1/img/rewind.gif" border="0" />

Categories