Clock count javascript/php error - php

http://www.juriseodesign.com/clock/Sydney.php
My clock count javascript shows errors. I have my background changes working, but after adding the count clock javascript, the clock doesn't work. I guess it is caused by "collisions" with Mootools and regular jQuery, but I don't have any idea how to fix it. Could anybody can help this for me? Also, how to connect to other paged when I click the one of the city in the dropdown menu?
Thank you so much!
// JavaScript Document
//initial time
var h_current = -1;
var m1_current = -1;
var m2_current = -1;
var s1_current = -1;
var s2_current= -1;
function flip (upperId, lowerId, changeNumber, pathUpper, pathLower){
var upperBackId = upperId+"Back";
$(upperId).src = $(upperBackId).src;
$(upperId).setStyle("height", "64px");
Uncaught TypeError: Object # has no method 'setStyle' (repeated 315 times)
$(upperId).setStyle("visibility", "visible");
$(upperBackId).src = pathUpper+parseInt(changeNumber)+".png";
$(lowerId).src = pathLower+parseInt(changeNumber)+".png";
$(lowerId).setStyle("height", "0px");
$(lowerId).setStyle("visibility", "visible");
var flipUpper = new Fx.Tween(upperId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
flipUpper.addEvents({
'complete': function(){
var flipLower = new Fx.Tween(lowerId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
flipLower.addEvents({
'complete': function(){
lowerBackId = lowerId+"Back";
$(lowerBackId).src = $(lowerId).src;
$(lowerId).setStyle("visibility", "hidden");
$(upperId).setStyle("visibility", "hidden");
} });
flipLower.start('height', 64);
}
});
flipUpper.start('height', 0);
}//flip
function retroClock(){
// get new time
now = new Date();
h = now.getHours();
m1 = now.getMinutes() / 10;
m2 = now.getMinutes() % 10;
s1 = now.getSeconds() / 10;
s2 = now.getSeconds() % 10;
if(h < 12)
ap = "AM";
else{
if( h == 12 )
ap = "PM";
else{
ap = "PM";
h -= 12; }
}
//change pads
if( h != h_current){
flip('hoursUp', 'hoursDown', h, 'Single/Up/'+ap+'/', 'Single/Down/'+ap+'/');
h_current = h;
}
if( m2 != m2_current){
flip('minutesUpRight', 'minutesDownRight', m2, 'Double/Up/Right/', 'Double/Down/Right/');
m2_current = m2;
flip('minutesUpLeft', 'minutesDownLeft', m1, 'Double/Up/Left/', 'Double/Down/Left/');
m1_current = m1;
}
if (s2 != s2_current){
flip('secondsUpRight', 'secondsDownRight', s2, 'Double/Up/Right/', 'Double/Down/Right/');
s2_current = s2;
flip('secondsUpLeft', 'secondsDownLeft', s1, 'Double/Up/Left/', 'Double/Down/Left/');
s1_current = s1;
}
}
setInterval('retroClock()', 1000);

I just looked at jQuery reference, setStyle method does not exist.
You should use css method instead :
$(upperId).css('height','64px;');
Looking at this code, there are many things, that don't match with jQuery methods.
For example: if you want change src attribute to upperId element, in jQuery you should use attr method:
// $(upperId).src = $(upperBackId).src; // WRONG
$(upperId).attr('src', $(upperBackId).attr('src')); // CORRECT
If you want reference an element with its id you must prepend # before the element id:
var upperBackId = "#" + upperId + "Back";

You try to use Mootools methods with jQuery. There is no setStyle() method in jQuery.

Like others have suggested you should use $(..).css( ...) function since setStyle does not exist in jQuery.
I usually also prefer to use $(...).hide() and $(...).show() instead of $(...).css("visibility","hidden") or $(...).css("visibility","visible") since "visibility" still takes space and is the same as setting opacity to 0 - If I hide the element, I don't want it to use any space...

Related

convert php to javascript #1

I'm trying to convert this awesome pathfinding php function from http://granularreverb.com/a_star.php to javascript.
PHP function
function path_float(&$heap, &$values, $i, $index) {
for (; $i; $i = $j) {
$j = ($i + $i%2)/2 - 1;
if ($values[$heap[$j]] < $values[$index])
break;
$heap[$i] = $heap[$j];
}
$heap[$i] = $index;
}
JAVASCRIPT function
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = j) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}
I'm not sure if javascript understands for() without all elements? If i try to execute javascript function my browser freezes.
P.s. i'm not interested in pre-written js pathdindings, because i need identical php and js function.
Thanks in advance
You can use for without all the elements in javascript similar to PHP. So that is not the problem.
I think the problem is the float that is returned to J. it could be that it never realy is 0 but might be some large float like 0.00000000001 or something and thus never evaluates to false. Unfortunately I cannot test it as You did not provide any input values.
Try the following:
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = parseInt(j)) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}

javascript strange malfunction

I have a website that consists of index.php and otherpage.php. Both of these pages use
include_once("header.inc")
header.inc implements a jscript file like this
<script type="text/javascript" src="script.js"></script>
the jscript file lets me use a nice looking dropdown menu.
the problem is that the menu only works properly on index.php, and not otherpage.php
What is really getting me is that on otherpage.php it's not that the menu doesnt work AT ALL, it just doesn't work partly. The menu will highlight but not dropdown.
You can see for yourself
index.php
otherpage.php
Is there something about sharing a jscript file between PHP pages that I should know?
Here are the relevant jscript contents for the menu:
var menu = function() {
var t = 15, z = 50, s = 6, a;
function dd(n) {
this.n = n;
this.h = [];
this.c = []
}
dd.prototype.init = function(p, c) {
a = c;
var w = document.getElementById(p), s = w.getElementsByTagName('ul'), l = s.length, i = 0;
for(i; i < l; i++) {
var h = s[i].parentNode;
this.h[i] = h;
this.c[i] = s[i];
h.onmouseover = new Function(this.n + '.st(' + i + ',true)');
h.onmouseout = new Function(this.n + '.st(' + i + ')');
}
}
dd.prototype.st = function(x, f) {
var c = this.c[x], h = this.h[x], p = h.getElementsByTagName('a')[0];
clearInterval(c.t);
c.style.overflow = 'hidden';
if(f) {
p.className += ' ' + a;
if(!c.mh) {
c.style.display = 'block';
c.style.height = '';
c.mh = c.offsetHeight;
c.style.height = 0
}
if(c.mh == c.offsetHeight) {
c.style.overflow = 'visible'
} else {
c.style.zIndex = z;
z++;
c.t = setInterval(function() {
sl(c, 1)
}, t)
}
} else {
p.className = p.className.replace(a, '');
c.t = setInterval(function() {
sl(c, -1)
}, t)
}
}
function sl(c, f) {
var h = c.offsetHeight;
if((h <= 0 && f != 1) || (h >= c.mh && f == 1)) {
if(f == 1) {
c.style.filter = '';
c.style.opacity = 1;
c.style.overflow = 'visible'
}
clearInterval(c.t);
return
}
var d = (f == 1) ? Math.ceil((c.mh - h) / s) : Math.ceil(h / s), o = h / c.mh;
c.style.opacity = o;
c.style.filter = 'alpha(opacity=' + (o * 100) + ')';
c.style.height = h + (d * f) + 'px'
}
return {
dd : dd
}
}();
Thanks for your time
On the index.php page you are forgetting
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
Put it at the bottom of otherpage.php or put it in a footer.php to be included at the bottom of the page.
seem that the second page (not the index.php) does not have the
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
so the menu isn't created.
index.php includes this code at the end of the page that initializes your menu:
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
otherpage.php does not include that code so the code is never initialized and hooked up to your HTML.
Incidentally, you can debug this kind of issue yourself by putting a breakpoint in the .init() method in your code. In index.php you see that the breakpoint is hit and if you look at the calling stack, you can see where it is called from. If you put the same breakpoint in otherpage.php, you can see that it is not hit, thus never called.

Split Problem Internet Explorer

After an earlier question relating to this error.
Error: unable to get value of the property ‘split’: object is null or undefined
An answer was offered to add the following code:
/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function (str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return cbSplit._nativeSplit.call(str, separator, limit);
}
var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
}
/* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
}
while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;
} // end `if (!cbSplit)`
// for convenience...
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
};
After trialling the code above and deleting caches it was found to do nothing...can anyone help at all, kind regards in advance.
Thanks EdoDodo for the above code but can you offer any further help as I am almost tearing my hair out and it did not work in the end, one point to note, the linked in button on the home page (if commented out) makes that site work for the home page and the error goes away but I really want the linked in buttons for each post excerpt on the home page.
site is:
www.mobileinquirer.com
Firefox shows me a script error on line 913 in this part of your script:
<script type="text/javascript">
// <![CDATA[
var disqus_shortname = 'mobileinquirer';
var disqus_domain = 'disqus.com';
(function () {
var nodes = document.getElementsByTagName('span');
for (var i = 0, url; i < nodes.length; i++) {
if (nodes[i].className.indexOf('dsq-postid') != -1) {
nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
url = nodes[i].parentNode.href.split('#', 1);
if (url.length == 1) url = url[0];
else url = url[1]
nodes[i].parentNode.href = url + '#disqus_thread';
}
}
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_domain + '/forums/' + disqus_shortname + '/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
//]]>
</script>
The specific error is on this line:
url = nodes[i].parentNode.href.split('#', 1);
and it's because parentNode does not have an href. This error has nothing to do with the split function. The code is trying to obtain the value of the href attribute on the parentNode, but there is no href attribute so that resolves to undefined so the call to split fails. It has nothing to do with the split function. The issue is that your markup is apparently wrong and what I think is disqus code is expecting an tag around a tag, but it isn't finding that.
If you look at line 664-665 in the mobilinquirer.com HTML source, you will find this sequence at that line and then several times following:
<p><span
class="dsq-postid">8 Comments</span></p>
This code causes the error. The <span class="dsq-postid"> tag must have an <a href="xxx"> tag as it's parent or you will get this error. I see this same problem several problems in your HTML.
This problem has NOTHING to do with the split function. To make this error go away, you need to fix your HTML so that it is what the disqus code is expecting or remove the offending disqus code (which you don't seem to need) or both.

Tooltips styling issue

Hi I'm using tooltips on my site to give links and certain images hints/descriptions. I wanted for my tooltips to be able to have different styles. I pass this variable into the JS file and the code does work to an extent..
The error I am receiving is: The first rollover I make sets the style for all other rollovers, even those that are sending a variable for a different style..
Mouseover HTML
(text, size, style) - this is an example of two different onmouseovers sending a diff style
onmouseover="tooltip.show('About Us', 89,'cont1');"
onmouseover="tooltip.show('Archive', 89,'cont2');"
JS
var tooltip=function(){
var id = 'tt';
var top = 3;
var left = 3;
var maxw = 300;
var speed = 10;
var timer = 40;
var endalpha = 95;
var alpha = 0;
var tt,t,c,b,h, no;
var ie = document.all ? true : false;
return{
show:function(v,w,no){
if(tt == null){
tt = document.createElement('div');
tt.setAttribute('id',id + no);
t = document.createElement('div');
t.setAttribute('id',id + 'top');
c = document.createElement('div');
c.setAttribute('id',id + 'text');
b = document.createElement('div');
b.setAttribute('id',id + 'bot');
tt.appendChild(t);
tt.appendChild(c);
tt.appendChild(b);
document.body.appendChild(tt);
tt.style.opacity = 0;
tt.style.filter = 'alpha(opacity=0)';
document.onmousemove = this.pos;
}
tt.style.display = 'block';
c.innerHTML = v;
tt.style.width = w ? w + 'px' : 'auto';
if(!w && ie){
t.style.display = 'none';
b.style.display = 'none';
tt.style.width = tt.offsetWidth;
t.style.display = 'block';
b.style.display = 'block';
}
if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
h = parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer = setInterval(function(){tooltip.fade(1)},timer);
},
pos:function(e){
var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
tt.style.top = (u - h) + 'px';
tt.style.left = (l + left) + 'px';
},
fade:function(d){
var a = alpha;
if((a != endalpha && d == 1) || (a != 0 && d == -1)){
var i = speed;
if(endalpha - a < speed && d == 1){
i = endalpha - a;
}else if(alpha < speed && d == -1){
i = a;
}
alpha = a + (i * d);
tt.style.opacity = alpha * .01;
tt.style.filter = 'alpha(opacity=' + alpha + ')';
}else{
clearInterval(tt.timer);
if(d == -1){tt.style.display = 'none'}
}
},
hide:function(){
clearInterval(tt.timer);
tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
}
};
}();
If I follow your code, it looks like your handing in style and using it as part of the name of the ID for the div your creating for the tool tip (I'm assuming your styling things based on ID name). If this is all true, it looks like your issue is that after the first tooltip is created (when tt == null at the top of your show function) you never change the ID of the tool tip after that. The ID only updates on create, so the style will not change once its created.
of course I could be completely wrong about this (I am after all out of coffee at this moment...)
Sorry for not actually answering your question, but you shouldn't invent the wheel. There're SO many libraries out there, that does the exact same thing. Here is 50 to get you started.

Creating an element and insertBefore is not working

Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!

Categories