I am currently working on a webpage, what I need to achieve is, when I click on an icon, a message box prompt out , and there is a count down timer on the message box, when I return the count down timer, it only return the value when I trigger it, but I would like to do a live count down timer in the message box , how can I do it??
Here is the JavaScript
function phyTimer3() {
var minutes1 = Math.floor(timeleft2 / 60);
var seconds1 = Math.floor(timeleft2 % 60);
if (timeleft2 > 0) {
timeleft2 -= 1;
} else {
autoRefresh = 1;
localStorage.setItem("translateX", translate.translateX);
localStorage.setItem("translateY", translate.translateY);
localStorage.setItem("scale", scale);
localStorage.setItem("autoRefresh", autoRefresh);
localStorage.setItem("zoomLevel", zoomLevel);
window.location.reload();
}
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
return ("Global Timer " + minutes1 + " : " + seconds1);
}
if (bs.monitoring_status == 1) {
if (bs.cooldown_duration == '') {
var timer1 = document.getElementById('timer2').value;
monitoringmsg = "Zone:" + bs.zone + " Site:" + bs.site + " Current Monitoring Status is On" +
"</br>" + "Do you want to turn it <strong>off</strong>?" + "</br>" + "Cooldown Timer : " + phyTimer3();
} else {
monitoringmsg = "Zone:" + bs.zone + " Site:" + bs.site + " Current Monitoring Status is On" +
"</br>" + "Do you want to turn it <strong>off</strong>?"
}
$("#manualSwitch").append($("<p/>").attr("id", "monitoringon").attr("title", "Monitoring Status").html(monitoringmsg));
$("#monitoringon").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
'Yes': function() {
$("#monitoring_zone_id").val(bs.zone);
$("#monitoring_site_id").val(bs.site);
$("#actionMonitoring").val('off');
document.forms["brSwitch"].submit();
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
}
The function phyTimer3 is where I return the minutes and seconds , but obviously this is not working , I am new to programming , I not sure what kind of function is working , can you guys help me on this ??
Related
I have developed a countdown timer function.
This function works fine. But the problem is it goes through the minus value too. So I want to stop the counting when its come to the 00:00:00.
How can I do this.please help me?
Javascript
function initCountdown() {
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval( interval ); }
if (seconds < 10) {
outputElement.innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
outputElement.innerHTML = hours + ": " + minutes + ": " + seconds + " "; }}
function count(){
time[2]--;
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
print();
}
var outputElement = document.getElementById('demo');
var time = document.getElementById("picker-dates1").value;
time = time.split(':'); }
HTML
<input type = "text" id = "picker-dates1"/>
<P id="demo"></p>
Replace print(); with if (time[0] >= 0) { print(); }
I'm using API sockets to update the market data.
and I want to classes change when the price goes up and down,
my first class (_class) is working successfully,
second class (_class2) is working at the start by changing to UP (pump) but it won't get back to down (dump) when the price goes down just like the first class. I'm in a bit of confusion coz I'm not so experienced at js.
can anyone tell me where I am mistaken?
window.updateMarkets = function (data) {
if (data.coin != undefined) {
var coin = 'BTC_' + data.coin;
var coin_data = data.msg;
var _coinTable = $('#coins-info-table');
var row = _coinTable.find("tr#" + coin);
price = _coinTable.find("tr#" + coin + " .price");
change = _coinTable.find("tr#" + coin + " .change");
volume = _coinTable.find("tr#" + coin + " .volume");
capital = _coinTable.find("tr#" + coin + " .market_capital");
supply = _coinTable.find("tr#" + coin + " .supply");
_price = formatter.format(coin_data.price);
previous_price = $(price).data('usd');
_class = coin_data.cap24hrChange >= 0 ? 'increment' : 'decrement';
_class2 = coin_data.cap24hrChange >= 0 ? 'pump' :'dump';
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
}
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
}
$(volume).html(formatter.format(coin_data.volume));
$(capital).html(formatter.format(coin_data.mktcap));
$(supply).html(coin_data.supply);
if (_price !== previous_price) {
_class = previous_price < _price ? 'increment' : 'decrement';
_class2 = previous_price < _price ? 'pump' : 'dump';
$(row).addClass(_class);
setTimeout(function () {
$(row).removeClass('increment decrement');
}, 300);
}
}
};
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.
I have this webpage with a puzzle game that is loading the game features before the image can be pulled from a url. How can I stall this so the image can be pulled before?
Been working on it for awhile, a detailed response please :)!
My webpage to show issue:
http://www.acsu.buffalo.edu/~jamesber/GameOne.html#
var plant = "";
$(function () {
$.ajax({"url":"http://beta.botanicalapp.com/api/v1/plants/?photo=true"})
.done(function(fullData){
plant = fullData[2].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);
$("#instruct").click(function(){$("final").dialog("open");
return 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 == 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");
}
}
});
}
}
});
how about running the function start game function with jquery on load
$('#imageID').on('load', function() {
startGame();
});
You could wrap startGame() function in
$( window ).load(function() {
startGame();
}
Run a function when the page is fully loaded including graphics.
https://api.jquery.com/load-event/
Check out this question:
Detect image load
Here is the answer that seems to solve your issue:
$("#myImg").load(function() {
alert('I loaded!');
}).attr('src', 'myImage.jpg');
Be sure to attach it before setting the source, or the event may have fired before you attached a handler to listen for it (e.g. loading from cache).
If that's not doable (setting the src after binding), be sure to check if it's loaded and fire it yourself, like this:
$("#myImg").load(function() {
alert('I loaded!');
}).each(function() {
if(this.complete) $(this).load();
});
The script I have works well, but I need an additional search field for city and I have some problems with this feature.
This is my code I have # this time.
jQuery code
$(function () { var DEG = 'c'; var weatherDiv = $('#weather'), scroller = $('#scroller'), location = $('div.location');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
function locationSuccess(position) {
try {
var cache = localStorage.weatherCache && JSON.parse(localStorage.weatherCache);
var d = new Date();
if (cache && cache.timestamp && cache.timestamp > d.getTime() - 30 * 60 * 1000) {
var offset = d.getTimezoneOffset() * 60 * 1000;
var city = cache.data.city.name;
var country = cache.data.city.country;
$.each(cache.data.list, function () {
var localTime = new Date(this.dt * 1000 - offset);
addWeather(
this.weather[0].icon,
moment(localTime).calendar() + ' Uhr',
this.weather[0].description,
'<span class="forecast-temp-blue">' + convertTemperature(this.main.temp_min) + '°' + DEG + '</span> | <span class="forecast-temp-red">' + convertTemperature(this.main.temp_max) + '°' + DEG + '</span>',
'<b>' + this.main.humidity + '%</b>',
'<b>' + miles2km(this.wind.speed) + '</b>',
'<b>' + convertDeg2Comp(this.wind.deg) + '</b>'
);
});
location.html(city + ', <b>' + country + '</b>');
weatherDiv.addClass('loaded');
showSlide(0);
} else {
var weatherAPI = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&lang=de&callback=?';
$.getJSON(weatherAPI, function (response) {
localStorage.weatherCache = JSON.stringify({
timestamp: (new Date()).getTime(),
data: response
});
locationSuccess(position);
});
}
} catch (e) {
showError("We can't find information about your city!");
window.console && console.error(e);
}
}
function addWeather(icon, day, description, temperature, humidity, windspeed, winddeg) {
var markup = '<li>' +
'<div class="row-body">' +
'<div class="forecast-day">' + day + '</div>' +
'<div class="forecast-cond">' + description + '</div>' +
'<img src="assets/img/icons/' + icon + '.png" /><br>' +
'<div class="forecast-left-side">' +
'<div class="forecast-temp"><img src="assets/img/icons/temp.png" />' + temperature + '</div>' +
'<div class="humidity"><img src="assets/img/icons/drop.png" />' + humidity + '</div>' +
'</div>' +
'<div class="forecast-right-side">' +
'<div class="wind"><img src="assets/img/icons/wind.png" />' + windspeed + ' km/h</div>' +
'<div class="windr"><img src="assets/img/icons/windr.png" />' + winddeg + '</strong></div>' +
'</div></div></li>';
scroller.append(markup);
}
var currentSlide = 0;
weatherDiv.find('a.previous').click(function (e) {
e.preventDefault();
showSlide(currentSlide - 1);
});
weatherDiv.find('a.next').click(function (e) {
e.preventDefault();
showSlide(currentSlide + 1);
});
$(document).keydown(function (e) {
switch (e.keyCode) {
case 37:
weatherDiv.find('a.previous').click();
break;
case 39:
weatherDiv.find('a.next').click();
break;
}
});
function showSlide(i) {
var items = scroller.find('li');
if (i >= items.length || i < 0 || scroller.is(':animated')) {
return false;
}
weatherDiv.removeClass('first last');
if (i == 0) {
weatherDiv.addClass('first');
} else if (i == items.length - 1) {
weatherDiv.addClass('last');
}
scroller.animate({
left: (-i * 100) + '%'
}, function () {
currentSlide = i;
});
}
function locationError(error) {
switch (error.code) {
case error.TIMEOUT:
showError("A timeout occured! Please try again!");
break;
case error.POSITION_UNAVAILABLE:
showError('We can\'t detect your location. Sorry!');
break;
case error.PERMISSION_DENIED:
showError('Please allow geolocation access for this to work.');
break;
case error.UNKNOWN_ERROR:
showError('An unknown error occured!');
break;
}
}
function convertTemperature(kelvin) {
return Math.round(DEG == 'c' ? (kelvin - 273.15) : (kelvin * 9 / 5 - 459.67));
}
function convertDeg2Comp(num) {
val = Math.round((num - 22.5) / 45);
arr = ["N", "NO", "O", "SO", "S", "SW", "W", "NW"];
return arr[val % 8];
}
function miles2km(num) {
val = (num / 0.62137).toFixed(2);
return val;
}
function showError(msg) {
weatherDiv.addClass('error').html(msg);
}
});
and here is my html code
<div id="weather">
<div class="location"></div>
<ul id="scroller">
<!-- The forecast items will go here -->
</ul>
Previous Next
<form id="search">
<input id="getcity" name="q" type="text" size="40" placeholder="Stadtname" onclick="httpGetCity()"/>
</form>
<input id="gloc" type="submit" title="W3C Geolocation" value="" />
</div>
The user should have the possibility to enter a city name and the weather data should be displayed in the same widget for the entered city.
How can we achieve this?