Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
When run this code the output like "2:40:17 PM", the div refreshed every second but the problem is the time never changed.
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
<script type="text/javascript">
function timedMsg()
{
var t=setInterval("change_time();",1000);
}
function change_time()
{
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if(curr_hour > 12)
curr_hour = curr_hour - 12;
document.getElementById('Hour').innerHTML =curr_hour+':';
document.getElementById('Minut').innerHTML=curr_min+':';
document.getElementById('Second').innerHTML=curr_sec;
}
timedMsg();
</script>
<table>
<tr>
<td>Current time is :</td>
<td id="Hour" style="color:green;font-size:large;"></td>
<td id="Minut" style="color:green;font-size:x-large;"></td>
<td id="Second" style="color:red;font-size:xx-large;"></td>
<tr>
</table>
use this way to display time........
enjoy the above script
You can use ajax to refresh the time:
Example:
<?php
if(#$_GET["action"]=="getTime"){
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1; // time output for ajax request
die();
}
?>
<div id="qwe">test</div>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
AX = new ajaxObject("?action=getTime", showTime)
AX.update(); // start Ajax Request
}
// CallBack
function showTime( data ){
document.getElementById('qwe').innerHTML = data;
}
</script>
<script type="text/javascript">
// Ajax Object - Constructor
function ajaxObject(url, callbackFunction) {
var that=this;
this.updating = false;
this.abort = function() {
if (that.updating) {
that.updating=false;
that.AJAX.abort();
that.AJAX=null;
}
};
this.update =
function(passData,postMethod) {
if (that.updating) { return false; }
that.AJAX = null;
if (window.XMLHttpRequest) {
that.AJAX=new XMLHttpRequest();
}else{
that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (that.AJAX==null) {
return false;
}else{
that.AJAX.onreadystatechange = function() {
if (that.AJAX.readyState==4) {
that.updating=false;
that.callback( that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML, that.AJAX.getAllResponseHeaders() );
that.AJAX=null;
}
};
that.updating = new Date();
if (/post/i.test(postMethod)) {
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+'timestamp='+that.updating.getTime();
that.AJAX.open("POST", uri, true);
that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.AJAX.setRequestHeader("Content-Length", passData.length);
that.AJAX.send(passData);
}else{
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+passData+'×tamp='+(that.updating.getTime());
that.AJAX.open("GET", uri, true);
that.AJAX.send(null);
}
return true;
}
};
var urlCall = url;
this.callback = callbackFunction || function (){};
}
</script>
Related
When I'm clicking on add marker, the marker is in the top left of maps and not in the center.
I know that I'm working on V2, but I need it to work so I can get myself some time to figure V3 out.
Can someone please help me to fix this?
Already tried:
map.setCenter() on different places, but nothing works.
This is the main script:
<script
src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=<?php echo $this->params->get('map_api_key');?>"
type="text/javascript"></script>
<script type="text/javascript">
//<!--
var map;
var marker;
var markeradded=false;
var markerfixed=false;
var current_point;
var catIcon;
function initialize()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(430, 315) });
map.setUIToDefault();
map.disableScrollWheelZoom();
geocoder = new GClientGeocoder();
map.checkResize()
}
}
window.addEvent('domready',function()
{
initialize();
//var mapSlider = new Fx.Slide('gb_maplocator', {duration: 1000});
var mapSlider = document.getElementById('gb_maplocator');
//var mapSlider = $('gb_maplocator');
<?php if( $this->data->published==0){?>
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = '0px';
mapSlider.style.overflow = 'hidden';
<?php } ?>
$$('.gb_map_controls').addEvent('click',function(){
if(this.getProperty('value')==1)
{
mapSlider.style.visibility = 'visible';
mapSlider.style.height = 'auto';
}
else if(this.getProperty('value')==0)
{
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = '0px';
mapSlider.style.overflow = 'hidden';
}
});
$('btnAddtomap').addEvent('click',
function(e) {
$('map_level').value=map.getZoom();
$('map_glat').value=current_point.lat();
$('map_glng').value=current_point.lng();
});
GEvent.addListener(map, "zoomend",
function(oldlevel,newlevel) {
$('map_level').value=newlevel;
});
GEvent.addListener(map, "dragend",
function() {
current_point=map.getCenter();
});
<?php
if( $this->pin->map_image )
{
?>
catIcon = new GIcon();
catIcon.image = '<?php echo JUri::root().$this->pin->map_image.".".$this->pin->extension;?>';
catIcon.shadow = '<?php echo JUri::root().$this->pin->shadow_image.".".$this->pin->extension;?>';
//catIcon.iconSize = new GSize(25.0, 32.0);
//catIcon.shadowSize = new GSize(42.0, 32.0);
catIcon.iconAnchor = new GPoint(12.0, 16.0);
catIcon.infoWindowAnchor = new GPoint(12.0, 16.0);
map.disableScrollWheelZoom();
<?php
}
if(abs($this->data->glat)==0&&abs($this->data->glng)==0)
{
$country=$mainframe->getUserState($option."countrytitle");
$region=$mainframe->getUserState($option."regiontitle");
$address= array();
if($region!= JText::_('ALL') && !empty($region)){
$address[]=$region;
}
if($country!= JText::_('ALL') && !empty($country)){
$address[]=$country;
}
array_filter ($address);
if(count($address)>0)
{
?>
showAddress('<?php echo implode(',',$address)?>');
<?php
}
else
{
?>
showAddress('<?php echo $this->params->get('map_default_address','Brisbane, Australia');?>');
<?php
}
}
else
{
if( ! $this->pin->map_image && $this->data->map_image )
{
?>
catIcon = new GIcon();
catIcon.image = '<?php echo JUri::root().$this->data->map_image.".".$this->data->extension;?>';
catIcon.shadow = '<?php echo JUri::root().$this->data->shadow_image.".".$this->data->extension;?>';
//catIcon.iconSize = new GSize(25.0, 32.0);
//catIcon.shadowSize = new GSize(42.0, 32.0);
catIcon.iconAnchor = new GPoint(12.0, 16.0);
catIcon.infoWindowAnchor = new GPoint(12.0, 16.0);
<?php }?>
current_point=new GLatLng(<?php echo $this->data->glat;?>,<?php echo $this->data->glng;?>);
map.setCenter(current_point,<?php echo $this->data->level;?>);
marker = new GMarker(current_point,{icon:catIcon,draggable:true});
GEvent.addListener(marker, "dragend",
function(latlng) {
current_point = latlng;
$('map_level').value=map.getZoom();
$('map_glat').value=latlng.lat();
$('map_glng').value=latlng.lng();
});
marker.disableDragging();
map.addOverlay(marker);
checkResize()
markeradded=true;
markerfixed=true;
$('addMarkerButton').disabled=true;
$('addMarkerButton').setHTML("<?php echo JText::_('REMOVE_MARKER');?>");
$('fixMarkerButton').setHTML("<?php echo JText::_('UNFIX_MARKER');?>");
$('map_level').value=map.getZoom();
$('map_glat').value=current_point.lat();
$('map_glng').value=current_point.lng();
<?php if($this->data->published==0){?>
mapSlider.style.visibility = 'hidden';
mapSlider.style.height = "0px";
mapSlider.style.overflow = 'hidden';
<?php }?>
<?php
}
?>
if(markeradded)
{
$('fixMarkerButton').disabled=false;
}
else
{
$('fixMarkerButton').disabled=true;
}
});
window.addEvent('unload',function(){GUnload()});
//-->
</script>
<div class="gb_madata_publish">
<label><?php echo JText::_('Activeer Google Maps');?>:</label><div class="gb_madata_publish_control"><?php echo $this->lists['status'];?></div>
</div>
<div class="gb_map_locator" id="gb_maplocator">
<a id="btnAddtomap"><?php echo JText::_('LOCATE_ADDRESS_TO_MAP');?></a>
<fieldset class="adminform"><input type="hidden" name="glat"
id="map_glat" /> <input type="hidden" name="glng" id="map_glng" /> <input
type="hidden" name="level" id="map_level" />
<div id="map_canvas" style="width: 430px; height: 315px"><script>checkResize() </script></div>
<br />
<div class="mapbuttons"><a id="addMarkerButton"><?php echo JText::_('ADD_MARKER');?></a>
<a id="fixMarkerButton"><?php echo JText::_('FIX_MARKER');?></a></div>
</fieldset>
</div>
<?php
}
?>
And this is the JavaScript file that is included:
/**
* Map controller buttons
*
*/
window.addEvent('domready', function() {
var country_id = '';
var region_id = '';
var address1 = '';
var address2 = '';
$('btnAddtomap')
.addEvent(
'click',
function(e) {
e = new Event(e);
e.stop();
if($('address1')== undefined && $('address2')== undefined) return false;
if($('country_id')!= undefined) country_id= $('country_id').value;
if($('region_id')!= undefined) region_id= $('region_id').value;
if($('address1')!= undefined) address1= $('address1').value;
if($('address2')!= undefined) address2= $('address2').value;
url = 'index.php?option=com_listbingo&format=raw&task=addons.map.admin.loadadd&cid='
+ country_id
+ '®ion_id='
+ region_id;
url += '&street=' + address2
+ '&address='
+ address1;
req = new Ajax(url, {
onComplete :showAddress,
method :'get',
evalscript :true
});
req.request();
setCenter()
});
$('addMarkerButton').addEvent(
'click',
function(e) {
e = new Event(e);
e.stop();
if (!markeradded) {
marker = new GMarker(current_point, { icon:catIcon,
draggable :true
});
$('map_level').value=map.getZoom();
$('map_glat').value=(0);
$('map_glng').value=(0);
map.addOverlay(marker);
marker.enableDragging();
}
});
});
Done, i solved it by not using hidden divs.
I have to create a countdown timer for a bidding website. The timer works properly when I put it outside of the while loop. However, id does not work inside the loop. What am I doing wrong? Here is my code:
<script>
var before=""
var current="ended"
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
function countdown(yr,m,d,id){
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==0){
document.getElementById(id).value=current
return
}
else
document.getElementById(id).value="Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before
setTimeout("countdown(theyear,themonth,theday,id)",1000)
}
</script>
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
countdown(<?php echo $date.','.$row['id'];?>)
</script>
<?php
}
}
?>
change setTimeout with this:
setTimeout(function(){countdown(theyear,themonth,theday,id);},1000)
you can make your function to jQuery function like that:
jQuery.fn.countdown = function(yr,m,d){
$that = $(this);
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0 && dhour==0 && dmin==0 && dsec==0){
$that.val(current);
return
}
else
$that.val("Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before);
setTimeout(function(){ $that.countdown(theyear,themonth,theday);},1000)
}
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
$("?php echo $row['id'] ?>").countdown(<?php echo $date?>);
</script>
<?php
}
}
?>
I have code:
$(function() {
$('#datepicker').datepicker({
beforeShowDay: daysToMarkAndLink
});
});
function daysToMarkAndLink(date) {
.....(if daysToMarkAndLink matches){
......(link goes here and also highlight);
}
return [false];
}
<?
$sql = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($sql))
{
print $row["time_added"];
}
?>
i want to do something like, highlight the only days i have in database also and link them on my news page, filter by date_added.
i want a very simple news calendar on jQuery datepicker.
thanks
To implement this, you need to use a mix of beforeShowDay and onSelect like this:
<input type="textbox" id="mydate"></input>
<script>
//<![CDATA[
var dateArray = new Array();
// generate these from mysql. Replace the date by your date field
dateArray.push({date: new Date('2011/7/5'), link: 'http://mylink1.com'});
dateArray.push({date: new Date('2011/7/6'), link: 'http://mylink2.com'});
dateArray.push({date: new Date('2011/7/10'), link: 'http://mylink3.com'});
dateArray.push({date: new Date('2011/7/15'), link: 'http://mylink4.com'});
function formatDate(date) // we use function to convert date to a string we can debug
{
var mon = date.getMonth(); // 0-based
var day = date.getDate(); // 1-based
var yyy = date.getFullYear();
return (mon+1)+'/'+day+'/'+yyy;
}
$(function(){
$("#mydate").datepicker({
beforeShowDay: function(date) {
var bFound = false;
var sDate = formatDate(date);
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
bFound = true;
break;
}
}
return [bFound,'',''];
},
onSelect: function(dateText, inst) {
var sDate = formatDate(new Date(dateText));
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
document.location.href = dateArray[i].link;
break;
}
}
}
});
});
//]]>
</script>
I am trying to implement a Javascript/PHP/AJAX clock into my website so that I can have a simple clock which can operate in different timezones (tutorial is here http://networking.mydesigntool.com/viewtopic.php?tid=373&id=31)
This itself works fine, but I already have a javascript stopwatch running on the page, and the 2 seem to clash and the clock won't display while the stopwatch is working.
This is the script for the clock:
<script type="text/javascript">
function loadTime ()
{
http_request = false;
if(window.XMLHttpRequest)
{
// Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
}
else if(window.ActiveXObject)
{ // IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
var parameters = "time=";
http_request.onreadystatechange = alertContents;
http_request.open('POST', 'time.php', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
result = http_request.responseText;
document.getElementById('clock').innerHTML = result;
}
}
}
</script>
<body onload="setInterval('loadTime()', 200);">
and this is the code for the stopwatch:
<script type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = 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);
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);
}
</script>
Could someone help me get them to work side-by-side please?
Thanks for any help
For one, your’re declaring an onload event handler in your HTML:
<body onload="setInterval('loadTime()', 200);">
which is consequently overwritten in script:
window.onload = function()
{
stopwatch('Start');
}
This means the original onload call is never executed.
You should try using addEventListener so you can add multiple event handlers to the same event.
A couple more points:
Don’t pass a string to setInterval and setTimeout, just pass the function itself. More efficient and less error-prone: setInterval(loadTime, 200);
Instead of writing all that JS code to work with different browsers, use jQuery, mootools, or one of the gazillion other frameworks. They make it a lot easier to get it right on all browsers.
Try this:
See the subtle '+=' instead of '=' !
window.onload += function()
{
stopwatch('Start');
}
I have this code so far that redirects the user after 5 seconds to the correct URL:
<?php
$url = $_GET['url'];
header("refresh:5;url=$url");
include('ads.php');
?>
Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!
<script type="text/javascript">
(function () {
var timeLeft = 5,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown">5</span>.
You can try this.
As this is a common beginner question; I just wanted to highlight that for best practise setInterval should, and can usually be avoided by using setTimeout recursively within a function.
For example:
var timer = 5,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
Excellent code by Kyle. I have modified the timer with a pause and resume button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
Here is my take on it, without variables outside of the function. Depends on jQuery.
function count_down_to_action(seconds, do_action, elem_selector)
{
seconds = typeof seconds !== 'undefined' ? seconds : 10;
$(elem_selector).text(seconds)
var interval_id = setInterval(function(){
if (seconds <= 0)
{
clearInterval(interval_id);
if (typeof do_action === 'function')
do_action();
}
else
$(elem_selector).text(--seconds);
},1000)
}
Here is an example using it http://jsfiddle.net/VJT9d/