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

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" />

Related

Auto record and allow to play once using JQuery

Hiii Everyone,
Below is the sample code for record.
<html>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording()" type="button" value="start recording" />
<input onclick="stopRecording()" type="button" value="stop recording and play" />
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
</script>
</body>
</html>
What I want to do is setInterval for 40 secs it will buffer for 40 secs like recording will start in 40secs timer will run after 40 secs it will show the play button to check audio recorded.Below I had added sample screenshots
Progress bar will show the recording..Similarly there will be some question with audio there I need to start recording once audio complete play.If anybody knows solution for this issue Please help me.Thanks for ur support
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style>
.center_div {
width: 500px;
height: 100px;
background-color: #f5f5f5;
border: 1px solid #808080;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
/* half width*/
margin-top: -50px;
/* half height*/
padding: 25px;
}
.recording_label {
display: block;
text-align: center;
padding: 10px;
font-family: sans-serif;
font-size: 1.1em;
margin-bottom: 25px;
}
.loader_bg {
min-width: 100%;
background: #c5c5c5;
min-height: 20px;
display: block;
}
.loader_bg1 {
min-width: 90%;
background: grey;
min-height: 20px;
display: inline-block;
position: relative;
top: -20px;
}
</style>
</head>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording();" type="button" value="start recording" />
<input onclick="stopRecording();" type="button" value="stop recording and play" />
<div class="center_div">
<span class="recording_label">Please wait...</span>
<span class="loader_bg"></span>
<span class="loader_bg1"></span>
</div>
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
$(function() {
var max = 40;
var count = max + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording...");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
startRecording();
recordingSec(40);
return;
}
$(".recording_label").html("Recording will begin in " + count + " sec.");
var percent = (count / max) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
});
function recordingSec(sec) {
var count = sec + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording stopped...Playing");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
stopRecording();
return;
}
$(".recording_label").html("Recording started [ " + (sec - count) + " / " + sec + " ] sec.");
var percent = (count / sec) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
}
</script>
</body>
</html>
Try To Use:
.btn-primary-success {
color: #fff;
background-color: #04b5e0;
border-color: #04b5e0;
}
.btn-primary-success:hover, .btn-primary-success:focus, .btn-primary-success:active, .btn-primary-success.active, .open .dropdown-toggle.btn-primary-success {
color: #fff;
background-color: #09a0c5;
border-color: #09a0c5;
}
Using Html Code:
<div style="text-align: left; padding: 10px;">
<label style="margin-right: 10px; font-size: 14px !important;">Dictate Status</label>
<a class="btn btn-primary-success pauseAudioDocWS pause" title="Pause" style="display: none; margin-right: 5px;"
data-value="">
<i class="imgpauseWS fa fa-lg fa-pause" style="cursor: pointer; margin: 2px 5px;"></i>
<b class="ppauseWS btn-primary-success">Pause</b></a>
<a class="btn btn-primary-success recordAudioDocWS inActiveWS" title="Start" style="margin-right: 20px;"
data-value="">
<b class="pplayWS">Click here to Start</b>
<i class="imgplayWS fa fa-lg fa-microphone" style="cursor: pointer; margin: 2px 5px;"></i>
</a>
<span class="stopwatchWS" style="display: none; margin-right: 10px;">00:00:00</span>
</div>
Download Audio and Timer File in github links:
https://github.com/fezalhalai/AudioRecorder.js
Using Jquery Code:
<script src="../js/StopTimer.js"></script>
<script src="../js/jquery.timer.js"></script>
<script src="../js/AudioRecorder.js"></script>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gif-recorder.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gumadapter.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/DetectRTC.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
var oldRecorderWS;
$('.recordAudioDocWS').click(function () {
var $this = $(this);
if (oldRecorderWS != undefined) {
if (oldRecorderWS != document.tmId) {
alert('Dictating Already In Progress, Please Stop Previous Dictating To Continue');
return;
}
}
var checkin_id = document.tmId;
localStorage.setItem('checkin_id', checkin_id);
localStorage.setItem('Tran_Type', 'W');
oldRecorderWS = document.tmId;
var roomId = document.tmId;
localStorage.setItem('roomId', roomId);
var isRecording = false;
$(".isActiveWS").each(function () {
if ($(this).hasClass('isActiveWS')) {
isRecording = true;
}
});
if (isRecording == true) {
document.isRecordActivityPerforms = true;
if (confirm('Dictating in progress do you want to stop and save?')) {
oldRecorderWS = undefined;
$this.next('span').css('display', 'none');
Example1.resetStopwatch();
$('.stoprecmessage').css('display', 'block');
$(".isActiveWS").each(function () {
$(this).addClass('inActiveWS');
$(this).removeClass('isActiveWS');
$(this).find('.pplayWS').text('Click here to Start');
//$(this).find('.imgplay').attr('src', 'img/play.png');
$(this).find('.imgplayWS').addClass('fa-stop');
$(this).find('.imgplayWS').addClass('fa-microphone');
$(this).attr('title', 'Start');
});
//$('.tbothers').css('pointer-events', 'auto');
$('.btn-ws-next').removeAttr('disabled', '');
$('.btn-ws-prv').removeAttr('disabled', '');
$this.prev('a').css('display', 'none');
$this.prev('a').addClass('pause');
StartRecording();
document.isRecordActivityPerform = false;
//$this.next().next('img').removeClass('hidden');
if ($(CurruntAudioRecRow).parent().parent().find('.hdtmvid').val() == document.tmId) {
$(CurruntAudioRecRow).parent().parent().find('td .audioList').removeClass();
$(CurruntAudioRecRow).parent().parent().find('td .REC').removeClass('hidden');
$(CurruntAudioRecRow).parent().parent().find('td .PEN').addClass('hidden');
}
}
}
else {
$('.btn-ws-next').attr('disabled', 'disabled');
$('.btn-ws-prv').attr('disabled', 'disabled');
document.isRecordActivityPerform = true;
$this.next('span').css('display', 'inline');
$this.next().next('img').addClass('hidden');
Example1.init($this.next('span'));
Example1.resetStopwatch();
Example1.Timer.toggle();
$this.removeClass('inActiveWS');
$this.addClass('isActiveWS');
$this.find('.pplayWS').text('Stop');
//$this.find('.imgplay').attr('src', 'img/stop.png');
$this.find('.imgplayWS').removeClass('fa-microphone');
$this.find('.imgplayWS').addClass('fa-stop');
$this.attr('title', 'Stop');
$this.prev('a').css('display', 'inline-table');
StartRecording();
}
});
$('.pauseAudioDocWS').click(function () {
document.isRecordActivityPerform = true;
var $this = $(this);
Example1.Timer.toggle();
var btnStartRecording = document.querySelector('#btn-start-recording');
if ($(this).hasClass('pause')) {
btnStartRecording.recordRTC.pauseRecording();
recordingPlayer.pause();
$(this).addClass('resume');
$(this).removeClass('pause');
$(this).find('.ppauseWS').text('Resume');
//$(this).find('.imgpause').attr('src', 'img/play.png');
$(this).find('.imgpauseWS').removeClass('fa-pause');
$(this).find('.imgpauseWS').addClass('fa-microphone');
$(this).attr('title', 'Resume');
$(this).next('a').css('pointer-events', 'none');
$(this).next('a').attr('disabled', 'disabled');
}
else if ($(this).hasClass('resume')) {
btnStartRecording.recordRTC.resumeRecording();
recordingPlayer.play();
$(this).addClass('pause');
$(this).removeClass('resume');
$(this).find('.ppauseWS').text('Pause');
//$(this).find('.imgpause').attr('src', 'img/pause.png');
$(this).find('.imgpauseWS').removeClass('fa-microphone');
$(this).find('.imgpauseWS').addClass('fa-pause');
$(this).attr('title', 'Pause');
$(this).next('a').css('pointer-events', 'auto');
$(this).next('a').removeAttr('disabled');
}
});
});
</script>

Disable button until a number is reached

So I have a code so when I press a button a number goes up.
This is the html:
<button type="button" class="btn btn-default" onclick="javascript:btnClick()">+1</button>
This is the JavaScript:
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
return true
}
So I have a button that has +1 so when I press it the number goes up
I need a button that is disabled until that number gets to 5 for example then becomes clickable, is that possible? I'm still learning Javascript,
All help is appreciated.
If the button is disabled, a user cannot interact with it.
Try the following
window.onload=function() {
var count =0;
document.getElementById("btn").addEventListener("click", function() {
count++;
if(count === 5) {
this.innerHTML = "5 clicks reached!";
}
});
};
<button id="btn">Click</button>
You could try something like this:
document.getElementById("button").disabled = true;
timesClicked = 0;
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
if(timesClicked > 5){
document.getElementById("button").disabled = false;
}
}
<button type="button" id="button" class="btn btn-default" onclick="btnClick()">+1</button>
[].forEach.call(document.querySelectorAll("[data-click-vote]"), function(btn) {
btn.addEventListener("click", vote);
});
function vote() {
this.innerHTML = this.value=Math.min(++this.value, 5);
}
<button value="0" name="movie1" data-click-vote>+1</button> The Revenant<br>
<button value="0" name="movie2" data-click-vote>+1</button> Dracula<br>
<button value="0" name="movie3" data-click-vote>+1</button> The Usual Suspect<br>
Multiple buttons
Updates simultaneously value and innerHTML
You can submit the values using a <form>
You can achieve your requirement with JS and CSS as in the below solution.
You haven't tagged it with CSS but you might want to look at this as well.
Button is simply a disabled span. Clicks are registered and when the count requirement is satisfied, it springs to life and handles your clicks with the actual handler code. (You can add a handler instead of printing a click count)
window.onload = function() {
var count = 1;
document.getElementById("btn").addEventListener("click", function() {
count++;
this.innerHTML = "+" + count;
if (count >= 5) {
this.className = "btnenabled";
this.innerHTML = "Print Click Count!";
if(count > 5) {
document.getElementById("counter").innerHTML= "Click Count is " + count;
}
}
});
};
.btnenabled {
width:200px;
background-color: blue;
padding: 3px;
border-radius: 3px;
color: white;
font-weight: bold;
display:block;
text-align:center;
}
.btnenabled:hover {
background-color:purple;
}
.btndisabled {
width:200px;
padding: 3px;
border-radius: 3px;
display:block;
text-align:center;
background-color: grey;
color: #F0F0F0;
font-weight: 100;
}
<span id="btn" class="btndisabled"> +1 </span>
<span id="counter"></span>

Fill a circle over time

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

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?

Categories