Selecting a clicked element based on its data attribute - javascript

I'm working on a personal trainer website that lets you choose the time of your training session. There are 6 times available: 5 mins, 10 mins, 15 mins, and so on. This is what I have so far.
I want to highlight the time that you've chosen. I've only tried to implement this for the top row of times, and when you click a time to highlight it the other ones don't get unhighlighted, but that is not why I'm asking this question. My problem is that when you click on a time, nothing happens. I've tried looking in the console and this is the error it throws:
What's wrong with my code?
$("body").append(
"<p class='text' id='CYTText'>Choose your session's time:</p>"
);
setUpCYT(350, 200, 0.8, 0.85);
function setUpCYT(littleXOffset, littleYOffset, littleScale, littleOpacity) {
for (i = 1; i < 4; i++) {
var timeSelectorElement = "[data='" + i + "']";
var timeSelectorName = "timeSelector"+i;
$("body").append(
"<p class='text' id='CYTTimerText' data='" + i + "' onclick='selectTime(" + timeSelectorElement + ")'>00:00</p>"
);
$("[data='" + i + "']").css({"left":littleXOffset * (i-2), "-webkit-transform":"scale(" + littleScale + ")", "opacity":littleOpacity});
timeSelectorName = new Timer(timeSelectorElement);
timeSelectorName.set(i*5,0);
}
for (i = 1; i < 4; i++) {
$("body").append(
"<p class='text' id='CYTTimerText' data='" + i+3 + "'>00:00</p>"
);
$("[data='" + i+3 + "']").css({"top":littleYOffset, "left":littleXOffset * (i-2), "-webkit-transform":"scale(" + littleScale + ")", "opacity":littleOpacity});
var timeSelectorElement = "[data='" + i+3 + "']";
var timeSelectorName = "timeSelector"+i+3;
timeSelectorName = new Timer(timeSelectorElement);
timeSelectorName.set((i+3)*5,0);
}
//select the middle
selectTime("[data='2']");
}
function selectTime(data) {
TweenLite.to($(data), 0.5, {
"-webkit-transform":"scale(1)",
"opacity":1
});
}
//timer function
function Timer (element) {
var minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000, self = this, timeLeftToNextSecond = 1000, running = false;
this.set = function(inputMinutes, inputSeconds) {
finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.add = function(inputMinutes, inputSeconds) {
finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.subtract = function(inputMinutes, inputSeconds) {
finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
if(finalTimeInSeconds < 0) {nextTask()}
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.reset = function() {
this.set(0,0);
}
this.print = function() {
displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.
$(element).text(displayMinutes + ":" + displaySeconds);
}
this.run = function() {
if (running == false) {
running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
interval = 1000;
var theColorIs = $(element).css("color");
ac = setTimeout(_f,interval);
}
ac = setTimeout(_f, interval);
}
}
this.stop = function() {
if (running == true) {
running = false;
stopped = new Date;
interval = 1000 - (stopped - secondStarted);
clearTimeout(ac);
}
}
}
body{
background-color: #02BFC1;
overflow:hidden;
margin: 0;
}
#font-face {
font-family: 'Bebas Neue';
font-style: normal;
font-weight: normal;
src: local('Bebas Neue'), url('BebasNeue.woff') format('woff');
}
.text {
color: #F1F2F0;
font-family:Bebas Neue;
-webkit-user-select: none;
cursor: default;
text-shadow: 3px 3px 2px rgba(0,0,0,0.2);
}
#CYTText {
text-align:center;
height: 100px;
position: absolute;
margin: auto;
top: 0;
bottom: 290px;
right: 0;
left: 0;
font-size:50px;
}
#CYTTimerText {
text-align:center;
height: 100px;
position: absolute;
margin: auto;
top: 0;
bottom: 150px;
right: 0;
left: 0;
font-size:95px;
}

The syntax error is caused by the string that you're passing to append():
$("body").append(
"<p class='text' id='CYTTimerText' data='" + i +
"' onclick='selectTime(" + timeSelectorElement + ")'>00:00</p>"
);
Let's print an instance of this string and examine it:
<p class='text' id='CYTTimerText' data='1' onclick='selectTime([data='1'])'>00:00</p>
Observe that the onclick handler is a code fragment delimited by single quotes:
onclick='selectTime([data='
We can fix this by replacing the single quotes with escaped double quotes:
$("body").append(
"<p class='text' id='CYTTimerText' data='" + i +
"' onclick=\"selectTime(" + timeSelectorElement + ")\">00:00</p>"
);
However, now we have another problem. An instance of the string looks like this:
<p class='text' id='CYTTimerText' data='1' onclick="selectTime([data='1'])">00:00</p>
The code for onclick is selectTime([data='1']), which is syntactically incorrect. The intention is to pass the string "[data='1']" to selectTime.
The inline HTML already uses double quotes to delimit the onclick value. How do we put double quotes inside this value? We have to use " for each double quote:
$("body").append(
"<p class='text' id='CYTTimerText' data='" + i + "' onclick=\"selectTime("" + timeSelectorElement + "")\">00:00</p>"
);
Now an instance of the string looks like this:
<p class='text' id='CYTTimerText' data='1' onclick="selectTime("[data='1']")">00:00</p>
That looks strange, but it will be correct once it has been inserted into the document.
After making that change, the code sort of works. It's still not right because you have layout problems, but at least you can click on the 15:00 time and see that the onclick handler calls selectTime correctly.
By the way, there are better approaches than building that complicated string. You can simplify the inline handler to onclick="selectTime(this)", where this will have the value of the object that was clicked. An even better way to go about it would be to avoid inline handler definitions. Instead, build a paragraph object and make a new function that you assign as a click handler.
Regardless of how you implement the onclick handler, you're left with the problem of overlapping timer elements. Your timers are paragraphs that you've absolutely positioned next to one another. The paragraphs stretch as wide as possible. Thus, the first timer is obscured by subsequent timers.
You can get rid of the overlap by displaying the timers as inline-block elements. To restrict the width of the layout, put everything into a wrapper div. The following snippet demonstrates this approach.
window.onload = function () {
$('#wrapTimers').append(
"<p class='text' id='CYTText'>Choose your session duration:</p>"
);
setUpCYT(350, 200, 0.8, 0.85);
};
function setUpCYT(littleXOffset, littleYOffset, littleScale, littleOpacity) {
for (i = 1; i < 4; i++) {
var timeSelectorElement = "[data='" + i + "']";
var timeSelectorName = "timeSelector"+i;
var s = "<p class='text timerContainer' data='" + i +
"' onclick=\"selectTime(this)\">00:00</p>";
//"' onclick=\"selectTime("" + timeSelectorElement + "")\">00:00</p>";
$('#wrapTimers').append(s);
$("[data='" + i + "']").css({"left":littleXOffset * (i-2), "-webkit-transform":"scale(" + littleScale + ")", "opacity":littleOpacity});
timeSelectorName = new Timer(timeSelectorElement);
timeSelectorName.set(i*5,0);
}
for (i = 1; i < 4; i++) {
$('#wrapTimers').append(
"<p class='text timerContainer' data='" + i+3 + "'>00:00</p>"
);
$("[data='" + i+3 + "']").css({"top":littleYOffset, "left":littleXOffset * (i-2), "-webkit-transform":"scale(" + littleScale + ")", "opacity":littleOpacity});
var timeSelectorElement = "[data='" + i+3 + "']";
var timeSelectorName = "timeSelector"+i+3;
timeSelectorName = new Timer(timeSelectorElement);
timeSelectorName.set((i+3)*5,0);
}
//select the middle
selectTime("[data='2']");
}
function selectTime(selector) {
TweenLite.to($(selector), 0.5, {
"-webkit-transform":"scale(1)",
"opacity":1
});
}
//timer function
function Timer (element) {
var minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000, self = this, timeLeftToNextSecond = 1000, running = false;
this.set = function(inputMinutes, inputSeconds) {
finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.add = function(inputMinutes, inputSeconds) {
finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.subtract = function(inputMinutes, inputSeconds) {
finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
if(finalTimeInSeconds < 0) {nextTask()}
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.reset = function() {
this.set(0,0);
}
this.print = function() {
displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.
$(element).text(displayMinutes + ":" + displaySeconds);
}
this.run = function() {
if (running == false) {
running = true;
var _f = function() {
secondStarted = new Date;
self.subtract(0, 1);
interval = 1000;
var theColorIs = $(element).css("color");
ac = setTimeout(_f,interval);
}
ac = setTimeout(_f, interval);
}
}
this.stop = function() {
if (running == true) {
running = false;
stopped = new Date;
interval = 1000 - (stopped - secondStarted);
clearTimeout(ac);
}
}
}
body {
background-color: #02BFC1;
overflow: hidden;
margin: 0;
}
#wrapTimers {
width: 800px;
margin: 40px auto;
text-align: center;
}
.text {
color: #F1F2F0;
font-family: Oswald, sans-serif;
-webkit-user-select: none;
cursor: default;
text-shadow: 3px 3px 2px rgba(0, 0, 0, 0.2);
}
#CYTText {
width: 800px;
margin: auto;
font-size: 50px;
}
.timerContainer {
text-align: center;
display: inline-block;
font-size: 95px;
margin: 0 10px;
}
<link rel="stylesheet" type="text/css"
href="https://fonts.googleapis.com/css?family=Oswald" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js"></script>
<div id="wrapTimers"></div>

There are a couple of simple issues. first off the string isn't being parsed correctly that is setting up the onclick
Closing quotes
It should look like this: onclick="selectTime("[data='2']")"
But it looks like this: onclick="selectTime([data=" 2'])'
Reference Error
There is also a scoping /reference error for the function selectTime the click is trying to call
Here is the full working example: http://jsfiddle.net/qLnLmgy6/2/
Hope that helps!

Related

JavaScript text is not showing

I am having trouble with this html loading javascript animation - from https://codepen.io/atunnecliffe/pen/siqjd
The script is not printing the text inside the javascript but the screen is fading out at the end, like in the codepen example. Here is the JS right now:
var textarea = $(".term");
var speed = 50; //Writing speed in milliseconds
var text = "sh andrew_website.sh";
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(function () {
if (i < text.length) runner();
else {
textarea.append("<br>");
i = 0;
setTimeout(function () {
feedbacker();
}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 1;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 2 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 4) + 1;
count += time;
setTimeout(function () {
if (i < output.length - 2) feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function () {
$(".load").fadeOut(1000);
}, 500);
}
}, time);
}
var output = [
One error that has occurred is the VAR speed is defined but not used anywhere in the JS code however I am at a loss of as to where it could be used. Any help would be appreciated, Thanks, Oliver.
Make sure to embed jQuery, works fine for me.
var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'sh andrew_website.sh';
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function() {
if (i < text.length)
runner();
else {
textarea.append("<br>")
i = 0;
setTimeout(function() {feedbacker();}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 1;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 2 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 4) + 1;
count += time;
setTimeout(
function() {
if (i < output.length - 2)
feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function() {$(".load").fadeOut(1000);}, 500);
}
},time);
}
var output = ["TESTING",
"WORKING",
"fsdfsdfsdfsdf",
"Initialising...", ""];
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="load">
<pre class="term">andrew#dev:~$ </pre>
</div>

innerHTML' of null for the time and class when time changes

I keep on getting Uncaught TypeError: Cannot set property 'innerHTML' of null on the time where it tells u the day, hour, minute. "timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '';" this the one always being error or when it closing time.it changes to the error or stays at the same line. am i writing it correct?
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'http://www.weebly.com/editor/uploads/1/1/3/4/11341626/custom_themes/599346900698327146/files/Gifs/OpenLightOff.png';
imgArray[1] = new Image();
imgArray[1].src = 'http://www.weebly.com/editor/uploads/1/1/3/4/11341626/custom_themes/599346900698327146/files/Gifs/OpenLightOn.gif';
var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var today = weekday[now.getDay()];
var dayOfWeek = now.getDay();
var hour = now.getHours();
var minutes = now.getMinutes();
var suffix = hour >= 12 ? "PM" : "AM";
var checkTime2 = function() {
var timeDiv2 = document.getElementById('timeDiv2');
//add AM or PM
// add 0 to one digit minutes
if (minutes < 10) {
minutes = "0" + minutes
};
if ((dayOfWeek == 1 || dayOfWeek == 2 || dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 0 ) && hour >= 6 && hour <= 21) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[1].src+'></center>';
timeDiv2.className = 'open';
}
else if ((dayOfWeek == 5 || dayOfWeek == 6) && hour >= 6 && hour <= 22){
hour = ((hour + 11) % 12 + 1);
timeDiv2.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[1].src+'></center>';
timeDiv2.className = 'open';
}
else {
if (hour == 0 || hour > 5) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}
timeDiv2.innerHTML = 'It\'s ' + today + ' ' + hour + ':' + minutes + suffix + '<br><center><img style="width:100%;top:0px;border-radius:10px;" src= '+imgArray[0].src+' ></center>';
timeDiv2.className = 'closed';
}
};
var currentDay = weekday[now.getDay()];
var currentDayID = "." + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //hightlights today in the view hours modal popup
checkTime2();
[id ^="timeDiv"]
{
width:100%;
background: transparent;
margin: 0 auto;
border-radius: 3px;
/* -webkit-box-shadow: 0 8px 16px -8px #adadad;
-moz-box-shadow: 0 8px 16px -8px #adadad;
box-shadow: 0 8px 16px -8px #adadad;*/
display:block;
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
}
.day {
display: inline-block;
float: left;
}
.time {
display: inline-block;
float: right
}
.today {
color: rgb(200, 85, 39);
font-weight: 600;
}
.closed {
color: rgba(231, 76, 60, 0.85);
}
.open {
position:relative;
color: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="timeDiv2"></div>
Since the timeDiv2 element is part of your DOM, the best chance is that you run the javascript code before the HTML is being completely loaded.
You can fix this by calling the checkTime2() function only once the page has completely loaded:
$(function() {
checkTime2();
});
You are attempting you manipulate your DOM before it has loaded, try one of the following.
1.
Load your script as the last part of your body.
2.
Use the DOMContentLoaded event.
document.addEventListener('DOMContentLoaded', function () {
/** Your code here... **/
});
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
3.
If you are using jQuery then,
$(document).ready(function () {
/** Your code here... **/
});

JavaScript Amount Of Time

I'm currently working on a project that will display the amount of time left in a certain time period based on the users current time. Here is the code.
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '15:55' ],
[ '07:00' , ]
];
updateTimePeriods();
setInterval(updateTimePeriods, 1000); // Update every second
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
list-style-type: none;
}
<div class="outer-box">
<ul id="periods"></ul>
</div>
My goal is only display to the user the amount of time left in the current time period instead of all of them. And if its in between a time period it shows the amount of time until the next one occurs. The issue is once all the times occur I need to tell him much time until the start of the next time which occurs on a different day. To elaborate, currently if all the time periods occur it displays a blank space because there is nothing to display and all the times are negative. I want to display the amount of time until the next days starting time.
You should break the for loop as you create the new LI element. This way it should only show the actual time period.
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
break;
}
}

Javascript game loads slow

I am trying to create a puzzle game with javascript. I am grabbing an image for the puzzle from a url and loading it into the main div. But when I load the webpage it takes a second until everything loads correctly. How can I get this to look smoother?
Thanks
My webpage with the bug at start up:
http://www.acsu.buffalo.edu/~jamesber/GameOne.html#
My code:
$(function (){
var plant = "";
$.ajax({"url":"http://beta.botanicalapp.com/api/v1/plants/?photo=true"})
.success(function(fullData){
plant = fullData[2].plant.image_default.url;
$("#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 timer;
var secs = 0;
var mins = 0;
var millsecs = 0;
var timeString = document.getElementById("time");
timeString.innerHTML = "00:00:00";
function update(){
if(millsecs == 100) {
secs++;
millsecs = 0;
if(secs == 60){
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);
}
start();
initSwap();
function initSwap() {
initDroppable($("#puzzle div"));
initDraggable($("#puzzle div"));
}
function initDraggable($elements) {
$elements.draggable({
appendTo: "body",
helper: "clone",
cursor: "move",
revert: "invalid"
});
}
$("#final").dialog({
autoOpen: false,
modal: true,
width: 900,
resizable: false,
height: 520,
position: [250,75],
dialogClass: "fixed-dialog",
draggable: false
});
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){
clearTimeout(timer);
$("#thePlant").attr("src",plant);
$("#final").dialog("open");
}
}
});
}
});
});
Everything is happening in the success / done callback of the Ajax call.
Even if the image is cached or anything like that, you still have the overhead of:
make HTTP connection
request resource
receive response
close connection
That's why there's a lag at startup.
You should start that Ajax call and handle the response with the image separately from rendering the rest of the page.
p.s.
You should switch .success to .done, because jQuery's new(er) Deferred objects prefer it, and the old methods are deprecated:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Snow until the end of the page

I have a script of snow for the site, I took it from this site. As you can see, the snow does not go the bottom of the page. How can I make it go to the bottom?
Source code:
var SNOW_Time;
var SNOW_dx, SNOW_xp, SNOW_yp;
var SNOW_am, SNOW_stx, SNOW_sty;
var i, SNOW_Browser_Width = $(document).width(), SNOW_Browser_Height = $(document).height();
SNOW_dx = new Array();
SNOW_xp = new Array();
SNOW_yp = new Array();
SNOW_am = new Array();
SNOW_stx = new Array();
SNOW_sty = new Array();
for (i = 0; i < SNOW_no; ++i) {
SNOW_dx[i] = 0;
SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - 50);
SNOW_yp[i] = Math.random() * SNOW_Browser_Height;
SNOW_am[i] = Math.random() * 20;
SNOW_stx[i] = 0.02 + Math.random() / 10;
SNOW_sty[i] = 0.7 + Math.random();
if (i == 0) document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
else document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
}
function SNOW_Weather() {
for (i = 0; i < SNOW_no; ++i) {
SNOW_yp[i] += SNOW_sty[i];
if (SNOW_yp[i] > SNOW_Browser_Height) {
SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - SNOW_am[i] - 30);
SNOW_yp[i] = 0;
SNOW_stx[i] = 0.02 + Math.random() / 10;
SNOW_sty[i] = 0.7 + Math.random();
}
SNOW_dx[i] += SNOW_stx[i];
document.getElementById("SNOW_flake" + i).style.top = SNOW_yp[i] + "px";
document.getElementById("SNOW_flake" + i).style.left = SNOW_xp[i] + SNOW_am[i] * Math.sin(SNOW_dx[i]) + "px";
}
SNOW_Time = setTimeout("SNOW_Weather()", 10);
}
SNOW_Weather();
It looks like it's determined by the variable SNOW_Browser_Height. $(document).height() doesn't return the proper height. You could use this instead:
document.body.getClientRects()[0].height

Categories

Resources