VeriSign Obtrusive JavaScript interfering with page function - php

I have this VeriSign script that is causing the javascript notifications on my site to say "undefined" instead of displaying the mesage
Verisign Code:
< !--dn = "www.mysite.com";
lang = "en";
tpt = "transparent";
vrsn_style = "WW";
splash_url = "https://trustsealinfo.verisign.com";
seal_url = "https://seal.verisign.com";
u1 = splash_url + "/splash?form_file=fdf/splash.fdf&dn=" + dn + "&lang=" + lang;
u2 = seal_url + "/getseal?at=0&sealid=2&dn=" + dn + "&lang=" + lang;
u3 = seal_url + "/getseal?at=1&sealid=2&dn=" + dn + "&lang=" + lang;
var sopener;
function vrsn_splash() {
if (sopener && !sopener.closed) {
sopener.focus();
} else {
tbar = "location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500";
var sw = window.open(u1, 'VRSN_Splash', tbar);
if (sw) {
sw.focus();
sopener = sw;
}
}
}
var MM_cVer = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin: 0;
var ver = -1;
var v_ua = navigator.userAgent.toLowerCase();
var re = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
ver = parseFloat(RegExp.$1);
}
var v_old_ie = (v_ua.indexOf("msie") != -1);
if (v_old_ie) {
v_old_ie = ver < 5;
}
function v_mact(e) {
var s;
if (document.addEventListener) {
s = (e.target.name == "seal");
if (s) {
vrsn_splash();
return false;
}
} else if (document.captureEvents) {
var tgt = e.target.toString();
s = (tgt.indexOf("splash") != -1);
if (s) {
vrsn_splash();
return false;
}
}
return true;
}
function v_mDown(event) {
if (document.addEventListener) {
return true;
}
event = event || window.event;
if (event) {
if (event.button == 1) {
if (v_old_ie) {
return true;
} else {
vrsn_splash();
return false;
}
} else if (event.button == 2) {
vrsn_splash();
return false;
}
} else {
return true;
}
}
function v_resized() {
if (pageWidth != innerWidth || pageHeight != innerHeight) {
self.history.go(0);
}
}
if (plugin) {
var words = navigator.plugins["Shockwave Flash"].description.split(" ");
for (var i = 0; i < words.length;++i) {
if (isNaN(parseInt(words[i], 10))) {
continue;
}
var MM_pVer = words[i];
}
var MM_play = MM_pVer >= MM_cVer;
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.appVersion.indexOf("Win") != -1)) {
document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
document.write('on error resume next \n');
document.write('MM_play = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_cVer)))\n');
document.write('</SCR' + 'IPT\> \n');
}
if (MM_play) {
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"');
document.write(' ID="s_s" WIDTH="100" HEIGHT="72" ALIGN="">');
document.write(' <PARAM NAME=movie VALUE="' + u3 + '"> <PARAM NAME=loop VALUE=false> <PARAM NAME=menu VALUE=false> <PARAM NAME=quality VALUE=best> <PARAM NAME=wmode VALUE=' + tpt + '> <PARAM NAME="allowScriptAccess" value="always">');
document.write(' <EMBED src="' + u3 + '" loop=false menu=false quality=best wmode=' + tpt);
document.write(' swLiveConnect=FALSE WIDTH="100" HEIGHT="72" NAME="s_s" ALIGN=""');
document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="https://www.macromedia.com/go/getflashplayer" allowScriptAccess="always">');
document.write(' </EMBED>');
document.write(' </OBJECT>');
} else {
document.write("<IMG NAME=\"seal\" BORDER=\"true\" SRC=\"" + u2 + "\" oncontextmenu=\"return false;\" alt=\"Click to Verify - This site has chosen a VeriSign SSL Certificate to improve Web site security\">");
if (document.addEventListener) {
document.addEventListener('mouseup', v_mact, true);
} else {
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = v_mact;
}
}
if (document.layers) {
pageWidth = innerWidth;
pageHeight = innerHeight;
window.onresize = v_resized;
}
}
if ((v_ua.indexOf("msie") != -1) && (ver >= 7)) {
var plat = -1;
var re = new RegExp("windows nt ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
plat = parseFloat(RegExp.$1);
}
if ((plat >= 5.1) && (plat != 5.2)) {
document.write("<div style='display:none'>");
document.write("<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>");
document.write("</div>");
}
}-->
Versign on Page code:
<script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.MySite.com&size=S&use_flash=YES&use_transparent=YES&lang=en"> </script>
Affected Javascript:
RemoveItem: function(itemId)
{
if(confirm(lang.CartRemoveConfirm)) {
document.location.href = "cart.php?action=remove&item="+itemId;
}
},

If the code with lang.CartRemoveConfirm belongs to you, it looks like an object with message strings. You should notice that the second row of the VeriSign script redefines lang as the string "en", overriding any value it might have before. Can you use some other variable name?

Same issue here, thinking about using an iframe for the seal on pages that use this lang (CS-Cart vs Verisign).

Related

Sorting of html-table with data from sql-query by clicking on field-name

I have an sql-database, where data can be read out by an html-form. The data are shown in an html-table, this works fine! However, I would like to make the table sortable, which means, that by clicking on the respective field-name the data should be sorted according to this field (ascending/descending). I have tried different javaScript-solutions including tablesorter.com that work well in "normal" tables, however, not in this table that is built dynamically with data from a database. Here is my code that creates the table (code without specific link to JavaScript-files):
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql) or die("Invalid query"); //Running the
query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
$row = mysqli_fetch_array($result);
if ($numrows > 0) {
echo "<table id=myTable class=tablesorter>";
echo "<thead><tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr></thead>";
echo "<tbody><tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr></tbody>";
}
echo "</table>";
}
}
mysqli_close($db);
?>
One of the javaScript-files I tried:
(function () {
"use strict";
var tableSort = function (tab) {
var titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[
0].getElementsByTagName("th");
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen == 0) return;
var nspalten = tz[0].cells.length;
var arr = new Array(nzeilen);
var sortiert = -1;
var sorttype = new Array(nspalten);
var sortbuttonStyle = document.createElement
('style'); // Stylesheet für Button im TH
sortbuttonStyle.innerText =
'.sortbutton { width:100%; height:100%; border:
none; background-color: transparent; font: inherit; color: inherit; text-
align: inherit; padding: 0; cursor: pointer; } .sortbutton::-moz-focus-
inner { margin: -1px; border-width: 1px; padding: 0; }';
document.head.appendChild(sortbuttonStyle);
var initTableHead = function (sp) { // Kopfzeile
vorbereiten
var b = document.createElement("button");
b.type = "button";
b.className = "sortbutton";
b.innerHTML = titel[sp].innerHTML;
b.addEventListener("click", function () {
tsort(sp);
}, false);
titel[sp].innerHTML = "";
titel[sp].appendChild(b);
}
var getData = function (ele, s) {
var val = ele.innerHTML;
if (!isNaN(val) && val.search(/[0-9]/) !
= -1) return val;
var n = val.replace(",", ".");
if (!isNaN(n) && n.search(/[0-9]/) !=
-1) return n;
sorttype[s] = "s"; // String
return val;
} // getData
var vglFkt_s = function (a, b) {
var as = a[sortiert],
bs = b[sortiert];
if (as > bs) return 1;
else return -1;
} // vglFkt_s
var vglFkt_n = function (a, b) {
return parseFloat(a[sortiert]) -
parseFloat(b[sortiert]);
} // vglFkt_n
var tsort = function (sp) {
if (sp == sortiert) arr.reverse(); //
Tabelle ist schon nach dieser Spalte sortiert, also nur Reihenfolge
umdrehen
else { // Sortieren
sortiert = sp;
if (sorttype[sp] == "n")
arr.sort(vglFkt_n);
else arr.sort(vglFkt_s);
}
for (var z = 0; z < nzeilen; z++)
tbdy.appendChild(arr[z][nspalten]); // Sortierte Daten zurückschreiben
} // tsort
// Kopfzeile vorbereiten
for (var i = 0; i < titel.length; i++) initTableHead(i);
// Array mit Info, wie Spalte zu sortieren ist,
vorbelegen
for (var s = 0; s < nspalten; s++) sorttype[s] = "n";
// Tabelleninhalt in ein Array kopieren
for (var z = 0; z < nzeilen; z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
arr[z] = new Array(nspalten + 1);
arr[z][nspalten] = tz[z];
for (var s = 0; s < nspalten; s++) {
var zi = getData(zelle[s], s);
arr[z][s] = zi;
// zelle[s].innerHTML
+= "<br>"+zi+"<br>"+sorttype[s]; // zum Debuggen
}
}
} // tableSort
var initTableSort = function () {
var sort_Table = document.querySelectorAll
("table.sortierbar");
for (var i = 0; i < sort_Table.length; i++) new
tableSort(sort_Table[i]);
} // initTable
if (window.addEventListener) window.addEventListener("DOMContentLoaded",
initTableSort, false); // nicht im IE8
})();
Another of the javaScript-files I tried:
( function() {
"use strict";
var JB_sortbutStyle = document.createElement('style'); // Stylesheet
für Button im TH
JB_sortbutStyle.innerText = 'button.sortbut { width:100%; height:100%;
border: none; background-color: transparent; font: inherit; color:
inherit; text-align: inherit; padding: 0; cursor: pointer; }
button.sortbut::-moz-focus-inner { margin: -1px; border-width: 1px;
padding: 0; }';
document.head.appendChild(JB_sortbutStyle);
var JB_Table = function(tab) {
var up = String.fromCharCode(9650);
var down = String.fromCharCode(9660);
// var up = String.fromCharCode(8593);
// var down = String.fromCharCode(8595);
// var up = String.fromCharCode(11014);
// var down = String.fromCharCode(11015);
var no = String.fromCharCode(160,160,160,160); // Idee: 9674 ???
var dieses = this;
var defsort = 0;
var startsort_u = -1,startsort_d = -1;
var first = true;
var ssort;
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen==0) return;
var nspalten = tz[0].cells.length;
var Titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[0].getElementsByTagName("th");
var Arr = new Array(nzeilen);
var ct = 0;
var sdir = new Array(nspalten);
var stype = new Array(nspalten);
var sortable = new Array(nspalten);
for(var i=0;i<nspalten;i++) {
stype[i] = "n";
sdir[i] = "u";
sortable[i] = false;
}
var initTableHead = function(t,nr) {
var b = document.createElement("button");
b.type = "button";
b.className = "sortbut"
b.innerHTML = t.innerHTML;
t.innerHTML = "";
if(window.addEventListener) b.addEventListener
("click",function() { dieses.sort(nr); },false);
b.title = 'Die Tabelle nach "'+b.textContent+'"
sortieren.';
t.appendChild(b);
sortsymbol.init(t,no);
if(t.className.indexOf("vorsortiert-")>-1) {
sortsymbol.set(t,down);
ssort = nr;
}
else if(t.className.indexOf("vorsortiert")>-1) {
sortsymbol.set(t,up);
ssort = nr;
}
if(t.className.indexOf("sortiere-")>-1) startsort_d=nr;
else if(t.className.indexOf("sortiere")>-1)
startsort_u=nr;
sortable[nr] = true;
} // initTableHead
var sortsymbol = {
init: function(t,s) {
var tt = t.querySelector("button");
var sp = tt.getElementsByTagName("span");
for(var i=0;i<sp.length;i++) {
if(!sp[i].hasChildNodes()) {
t.sym = sp[i].appendChild
(document.createTextNode(s));
break;
}
}
if(typeof(t.sym)=="undefined") t.sym =
tt.appendChild(document.createTextNode(s));
},
set: function(t,s) {
t.sym.data = s;
},
get: function(t) {
return t.sym.data;
}
} // sortsymbol
var VglFkt_s = function(a,b) {
var as = a[ssort], bs = b[ssort];
var ret=(as>bs)?1:(as<bs)?-1:0;
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { as = a[defsort]; bs
= b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort])
}
return ret;
} // VglFkt_s
var VglFkt_n = function(a,b) {
var ret = parseFloat(a[ssort])-parseFloat(b[ssort]);
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { var as = a
[defsort],bs = b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort]);
}
return ret;
} // VglFkt_n
var convert = function(val,s) {
var dmy;
var trmdat = function() {
if(dmy[0]<10) dmy[0] = "0" + dmy[0];
if(dmy[1]<10) dmy[1] = "0" + dmy[1];
if(dmy[2]<10) dmy[2] = "200" + dmy[2];
else if(dmy[2]<20) dmy[2] = "20" + dmy[2];
else if(dmy[2]<99) dmy[2] = "19" + dmy[2];
else if(dmy[2]>9999) dmy[2] = "9999";
}
if(val.length==0) val = "0";
if(!isNaN(val) && val.search(/[0-9]/)!=-1) return val;
var n = val.replace(",",".");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
n = n.replace(/\s| | |\u00A0/g,"");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
dmy[5] = val.substring(dp+4,dp+6);
for(var i=0;i<6;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<6;i++) if(dmy[i]<10) dmy[i] = "0"
+ dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]+dmy[5]).replace(/ /g,"");
}
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
for(var i=0;i<5;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<5;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<3;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]+"."+dmy[2]).replace
(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<2;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<2;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+/)) {
dmy = val.split(".");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
return (""+dmy[2]+dmy[1]+dmy[0]).replace
(/ /g,"");
}
stype[s] = "s";
// return val.toLowerCase().replace(/
\u00e4/g,"ae").replace(/\u00f6/g,"oe").replace(/\u00fc/g,"ue").replace(/
\u00df/g,"ss");
return val.toLowerCase().replace(/\u00e4/g,"a ").replace
(/\u00f6/g,"o ").replace(/\u00fc/g,"u ").replace(/\u00df/g,"ss");
} // convert
this.sort = function(sp) {
if(sp<0 || sp>=nspalten) return;
if(!sortable[sp]) return;
if (first) {
for(var z=0;z<nzeilen;z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
Arr[z] = new Array(nspalten+1);
Arr[z][nspalten] = tz[z];
for(var s=0;s<nspalten;s++) {
if (zelle[s].getAttribute("data-
sort_key"))
var zi = convert(zelle
[s].getAttribute("data-sort_key"),s);
else if (zelle[s].getAttribute
("sort_key"))
var zi = convert(zelle
[s].getAttribute("sort_key"),s);
else
var zi = convert(zelle
[s].textContent,s);
Arr[z][s] = zi ;
// zelle[s].innerHTML
+= "<br>"+zi; // zum Debuggen
}
}
first = false;
}
if(sp==ssort) {
Arr.reverse() ;
if ( sortsymbol.get(Titel[ssort])==down )
sortsymbol.set(Titel[ssort],up);
else
sortsymbol.set(Titel[ssort],down);
}
else {
if ( ssort>=0 && ssort<nspalten ) sortsymbol.set
(Titel[ssort],no);
ssort = sp;
if(stype[ssort]=="s") Arr.sort(VglFkt_s);
else Arr.sort(VglFkt_n);
if(sdir[ssort]=="u") {
sortsymbol.set(Titel[ssort],up);
}
else {
Arr.reverse() ;
sortsymbol.set(Titel[ssort],down);
}
}
for(var z=0;z<nzeilen;z++)
tbdy.appendChild(Arr[z][nspalten]);
if(typeof(JB_aftersort)=="function") JB_aftersort
(tab,tbdy,tz,nzeilen,nspalten,ssort);
} // sort
if(!tab.title.length) tab.title="Ein Klick auf die
Spalten\u00fcberschrift sortiert die Tabelle.";
for(var i=Titel.length-1;i>-1;i--) {
var t=Titel[i];
if(t.className.indexOf("sortier")>-1) {
ct++;
initTableHead(t,i);
defsort = i ;
if(t.className.indexOf("sortierbar-")>-1) sdir
[i] = "d";
}
}
if(ct==0) {
for(var i=0;i<Titel.length;i++)
initTableHead(Titel[i],i);
defsort = 0;
}
if(startsort_u>=0) this.sort(startsort_u);
if(startsort_d>=0) { this.sort(startsort_d); this.sort
(startsort_d); }
if(typeof(JB_aftersortinit)=="function") JB_aftersortinit
(tab,tbdy,tz,nzeilen,nspalten,-1);
} // JB_Table
var JB_initTableSort = function() {
if (!document.querySelectorAll) return;
var JB_Tables = [];
var Sort_Table = document.querySelectorAll("table.sortierbar,
table[sortable]");
for(var i=0;i<Sort_Table.length;i++) JB_Tables.push(new JB_Table
(Sort_Table[i]));
var pars = decodeURI(window.location.search.substring(1));
if(pars.length) { // jbts=((0,1),(10,0),(3,3),(2,2)) tnr,snr
pars = pars.replace(/\s/g,"");
pars = pars.match(/jbts=\(?(\(\d+,\d+\),?){1,}\)?/gi);
if(pars) {
pars = pars[0].substr(pars[0].search("=")+1);
pars = pars.replace(/\(\(/g,"(").replace(/\)
\)/g,")").replace(/\)\(/g,")|(").replace(/\),\(/g,")|(");
pars = pars.split("|");
for(var i=0;i<pars.length;i++) {
var p = pars[i].substring(1,pars
[i].length-1).split(",");
if(p[0]>-1&&p[0]<JB_Tables.length)
JB_Tables[p[0]].sort(p[1]);
}
}
}
} // initTableSort
if(window.addEventListener) window.addEventListener
("DOMContentLoaded",JB_initTableSort,false);
})();
I would be more than happy if anybody could help me with this Problem!
I used tablesorter for same purpose. I created table dynamically from database and it worked. First add to table id="myTable". After just call the script by adding code below:
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
Note: Don't forget to include src="jquery.tablesorter.js" (download it from download link).
Now you should be able to sort your table by all columns by just clicking on table header of column.
EDIT:
Insted of:
echo "<table id=myTable class=tablesorter>";
Put:
echo "<table id='myTable' class='tablesorter'>";
How about sorting the table before displaying?
For example, if your link to the page is:
http://example.com/view/product_table
The code for querying the table is:
function getTable($order = null) {
$statement = "SELECT * FROM product_table";
if ($order) {
// switch case to prevent sql injection
switch ($order) {
case: "price":
$statement .= " ORDER BY product_price";
break;
}
}
// Continue the build sql here
}
Have the sorting button redirect to:
http://example.com/view/product_table?sort=price
Call function by:
getTable($GET[sort]);
To further my answer
I would suggest separating the code responsible for displaying and the code for building data
Name your variable to something more meaningful
Currently your code is very hard to maintain and read.

Caluclation of a Vat from a value of a javascript function

Hello everyone I need help
then I have a form that through a javascript function I calculate the total of a product and then mail
Now I want to calculate the VAT on that value , but it does not work and I understand why , perhaps , the value that gives me is a value not a number for example he gives me 100 Euros .. not 100 and then I wanted to know , if is a system to extract the number to that value and then let him calculate the VAT
thank you
I guess this is what you need..
Try explode(). This function returns you an array of strings.
$valueWithCurrency = "100 Euros";
$extractedValue = explode(' ', $valueWithCurrency); //space as a delimiter in first argument
echo $extractedValue[0]; //Here you go. "100"
echo $extractedValue[1]; //this contains "Euros"
sorry .
This is the plug-in code that I purchased
(function($) {
$.fn.SimplePriceCalc= function (options) {
// Default options for text
var settings = $.extend({
totallabel: "Total:",
detailslabel: "Details:",
currency:"$"
}, options );
// Initialize Variables
var total=0;
var child=this.find('*');
var formdropdowns=this.find('select');
this.addClass("simple-price-calc");
InitialUpdate();
// Change select data cost on each change to current selected value
formdropdowns.change( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
if($(this).data('mult') >= 0)
$("#simple-price-total label").attr('data-mult',selectedOption.val());
else
$(this).attr('data-total',selectedOption.data('price')) ;
}
UpdateTotal();
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").change( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1; } else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
UpdateTotal();
});
$(".simple-price-calc input[type=checkbox]").change( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
UpdateTotal();
});
$(".simple-price-calc input[type=radio]").change( function() {
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
});
//Initialize all fields if data is there
function InitialUpdate() {
formdropdowns.each( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
$(this).attr('data-total',selectedOption.data('price')) ;
}
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").each( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1;} else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
});
$(".simple-price-calc input[type=checkbox]").each( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
}
//Change value of total field by adding all data totals in form
function UpdateTotal() {
total=0;
totalmult=$(".simple-price-calc #simple-price-total label").attr("data-mult");
//For each input with data-merge attr, take merge ids value and multiply by current data-price
$("input[data-merge]").each(function(){
var ids=$(this).data('merge');
var ids=ids.split(',');
var arraytotals=1;
$.each(ids, function(key,value) {
var inputid =$("#"+value);
if( (inputid.attr('type') == 'checkbox' || inputid.attr('type') == 'radio') && inputid.is(':checked') )
arraytotals*=$("#"+value).val();
else if (inputid.attr('type') == 'text')
arraytotals*=$("#"+value).val();
else if (inputid.prop('nodeName') == "SELECT")
arraytotals*=$("#"+value).attr('data-total');
});
var idtotal=arraytotals;
if($.isNumeric(idtotal)) {
var pricecost=parseFloat($(this).data('price')) || 0;
$(this).val(idtotal);
var updpricecost= pricecost * parseFloat($(this).val());
$(this).attr('data-total',updpricecost);
}
});
child.each(function () {
itemcost= $(this).attr("data-total") || 0;
total += parseFloat(itemcost);
});
if(totalmult) { total = total * parseFloat(totalmult); }
$(".simple-price-calc #simple-price-total label").html(settings.currency+$.number(total,2));
setTimeout(function() {
UpdateDescriptions();
}, 100);
}
//Update Field Labels and Pricing
function UpdateDescriptions() {
var selectedformvalues= [];
var currtag='';
$(".simple-price-calc").find('*').each( function () {
currtag=$(this).prop('tagName');
if(currtag == "SELECT") {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
if (selectedOptions != '')
{
selectedOptions.each( function() {
var optionlabel= $(this).data('label') || '';
var optionprice = $(this).data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel + ": " + settings.currency + optionprice);
}
});
}
}
else{
var selectedOption = $(this).find(':selected');
if (selectedOption != '')
{
var optionlabel= selectedOption.data('label') || '';
var optionprice = selectedOption.data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel +": " + settings.currency + optionprice);
}
}
}
} // End of Form dropdown
if(currtag == "INPUT" && $(this).attr('type') == "text")
{
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else { var usernumber = 1; }
var pricecost=parseFloat($(this).data('price')) || 0;
var currlabel= $(this).attr('data-label') || '';
var currinput= userinput;
if (currlabel != '' && currinput !='') {
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
selectedformvalues.push(currlabel + ": " + settings.currency + updpricecost);
}
else{
selectedformvalues.push(currlabel + ": " + currinput);
}
}
}
} // End of input type text
if($("input[type=checkbox]") || $("input[type=radio]") )
{
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
var currlabel= $(this).attr('data-label') || '';
var currprice= checkboxval;
if (currlabel != '') { selectedformvalues.push(currlabel + ": " + settings.currency + currprice); }
}
}
} // End of input type checkbox or radio
});
$("#simple-price-details").html("");
if (selectedformvalues != '') {
$("#simple-price-details").append("<h3>"+ settings.detailslabel +"</h3>");
$.each(selectedformvalues, function(key,value) {
$("#simple-price-details").append(value + "<br />");
});
}
}// End of UpdateDescriptions()
this.append('<div id="sidebar"><div id="simple-price-total"><h3 style="margin:0;">' + settings.totallabel + ' </h3><label id="simple-price-total-num"> ' + settings.currency + $.number(total,2) + ' </label></div> <div id="simple-price-details"></div></div>');
return this;
}; // End of plugin
}(jQuery));
This is the call in html
// Attaches Simple Price Calc to form
$("#quoteform").SimplePriceCalc();
// Adds Total price and details to hidden inputs that can be used to e-mail data
$("form :input, form textarea, form select").change( function() {
setTimeout( function() {
var total=$('#simple-price-total-num').html();
var details=$('#simple-price-details').html();
$('#hiddentotal').val(total);
$('#hiddendetails').val(details);
}, 150);
});
in php use this to have the value
echo $_POST['hidden_total']

onload not calling my JS function?

i added this JS code:
<script language="JavaScript" type="text/JavaScript">
var receiveReq = getXmlHttpRequestObject();
var mTimer;
var url = "www-rainbowcode-net/apps_dev.php/messagebox/list";
function getXmlHttpRequestObject()
{
alert("in gethttprequest");
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
//document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.';
}
}
function getNewMessage()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
alert("state is" + receiveReq.readyState);
//var params = "name" + name + "&" + "comment=" + comment;
receiveReq.open("POST", url, true);
receiveReq.onreadystatechange = processReqChange;
receiveReq.send(null);
}
}
function processReqChange()
{
// only if req shows "loaded"
if (receiveReq.status == 200)
{
alert("processed" + receiveReq.responseText);
document.getElementById("message_area").innerHTML = receiveReq.responseText;
}
else
{
alert("There was a problem retrieving the XML data:\n" +
receiveReq.statusText);
}
mTimer = setTimeout('getNewMessage();',2000);
}
</script>
then i have my html mixed with php:
<body onload = "return getNewMessage();">
<table width='96%' border='0'>
<?php
$cursor = $pager->getFirstIndice();
foreach ($pager->getResults() as $msg)
{
$has_freechat = false;
//changed id to withid here
$freechat_req_link="profiles/confirmfreechat?withid=".$msg->getRcProfileTableRelatedByProfileIdFrom()->getId();
$freechat_req_link=link_to('Freechat',$freechat_req_link,'class=link_small_dark');
$cc = sizeof ($fc_records);
for($i = 0; $i < $cc; $i++)
{
if($fc_records[$i]->getProfileIdWith() == $msg->getProfileIdFrom())
{
$has_freechat = true;
break;
}
}
$unique_code_from = $msg->getRcProfileTableRelatedByProfileIdFrom()->getUniqueCode();
$block_url = link_to('Block User',"blocklist/block?unqiue_code=$unique_code_from",'class=link_medium_blue');
echo "<div id = 'message_area'>";
echo "<tr>";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "<td class='td_show_contact_item' align='left'>".$date."</td>";
$opened_once = $msg->getOpenedOnce();
if($opened_once >= 1)
{
echo "<td class='td_show_contact_item' align='left'>".link_to($msg->getSubject(), 'messagebox/read?cursor='.$cursor,'class=link_medium_blue')."</td>";
}
else
{ ?>
<td align='left'>
<a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?> </a>
</td>
<?php
}
echo "<td class='td_show_contact_item' align='left'>".$unique_code_from." ( $block_url )</td>";
echo "</tr>";
echo "</div>";
++$cursor;
}
</table>
can anybody tell me why my alerts in the 2nd and 3rd function dont execute? the one in the 1st executes
thanks
in getNewMessage you miss () for processReqChange
update:
function getNewMessage()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
alert("state is" + receiveReq.readyState);
//var params = "name" + name + "&" + "comment=" + comment;
receiveReq.open("POST", url, true);
receiveReq.onreadystatechange = processReqChange;
receiveReq.send(null);
}
mTimer = setTimeout("getNewMessage()", 5000);
}

addEventListener() attached to multiple buttons, but only fires once

I am writing a Facebook app in PHP/FBJS. I have some code where I attach an addEventListener() to two buttons. When I run the app, the first button I click on fires the addEventListener() and the event handler is invoked as expected. But if I click on the second button or click on the same button again, the event handler is not invoked. Here is my code:
//PHP
public function loadCargoDialogFbjsAction() {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$loadableCargo = $this->getRequest()->getPost('loadableCargo');
$fbjs =
'<div id="load_cargo_select">
<form id="load_cargo_select_form" action="" method="POST">
<p>Your train has stopped in the city of ' . $loadableCargo['city'] . '</p>
<p>' . $loadableCargo['city'] . ' produces the following goods:</p>
<ul>';
if(count($loadableCargo['city_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['city_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>Your train is hauling the following goods:</p>
<ul>';
if(count($loadableCargo['train_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['train_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>What would you like to do?</p>
<input type="button" id="load-new-submit" name="load-cargo-new" value="Load new goods" />
<input type="button" id="discard-existing-submit" name="load-cargo-discard" value="Discard existing goods" />
</form>
</div>';
echo $fbjs;
}
// JavaScript/FBJS
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', cargoEventHandler); //discardExistingCargo);
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
dialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
dialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
function cargoEventHandler(evt) {
//new Dialog().showMessage('loadNewCargo', 'city id='+cityId+', train id='+trainId);
//debugger;
cityId = evt.target.cityId;
trainId = evt.target.trainId;
switch(evt.target.getId()) {
case 'load-new-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Load new goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
openCargoHolds = data.openCargoHolds;
cargoHoldsUsed = 0;
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'cityGoods': data.cityGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
//debugger;
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Load cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-new', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-new-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
case 'discard-existing-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Discard existing goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'trainGoods': data.trainGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
var dialog = new Dialog().showChoice('Discard Cargo', fbjsData, 'Discard cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-discard', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-discard-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
}
return false;
}
Any help would be greatly appreciated. Thanks!
#Tim
I changed my loadCargo() function as follows to prevent duplication of those elements, but I am still running into the same problem as before.
var loadCargoDialog;
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
if(loadCargoDialog == null) {
loadCargoDialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler, true); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', discardExistingCargo, true);
} else {
loadCargoDialog.showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
}
loadCargoDialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
loadCargoDialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
loadCargoDialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
It looks like you might be creating elements with the same id. That would cause it to break.

FAQ displaying style in JavaScript

I have implemented the following JavaScript in my FAQ page:
var Spry;
if (!Spry) Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.CollapsiblePanel = function(element, opts)
{
this.init(element);
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
this.attachBehaviors();
};
Spry.Widget.CollapsiblePanel.prototype.init = function(element)
{
this.element = this.getElement(element);
this.focusElement = null;
this.hoverClass = "CollapsiblePanelTabHover";
this.openClass = "CollapsiblePanelOpen";
this.closedClass = "CollapsiblePanelClosed";
this.focusedClass = "CollapsiblePanelFocused";
this.enableAnimation = true;
this.enableKeyboardNavigation = true;
this.animator = null;
this.hasFocus = false;
this.contentIsOpen = true;
};
Spry.Widget.CollapsiblePanel.prototype.getElement = function(ele)
{
if (ele && typeof ele == "string")
return document.getElementById(ele);
return ele;
};
Spry.Widget.CollapsiblePanel.prototype.addClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Widget.CollapsiblePanel.prototype.removeClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
return;
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Widget.CollapsiblePanel.prototype.hasClassName = function(ele, className)
{
if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)
return false;
return true;
};
Spry.Widget.CollapsiblePanel.prototype.setDisplay = function(ele, display)
{
if( ele )
ele.style.display = display;
};
Spry.Widget.CollapsiblePanel.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
if (!optionsObj)
return;
for (var optionName in optionsObj)
{
if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
continue;
obj[optionName] = optionsObj[optionName];
}
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOver = function()
{
this.addClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOut = function()
{
this.removeClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.open = function()
{
this.contentIsOpen = true;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, true);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "block");
this.removeClassName(this.element, this.closedClass);
this.addClassName(this.element, this.openClass);
};
Spry.Widget.CollapsiblePanel.prototype.close = function()
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "none");
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabClick = function()
{
if (this.isOpen())
this.close();
else
this.open();
this.focus();
};
Spry.Widget.CollapsiblePanel.prototype.onFocus = function(e)
{
this.hasFocus = true;
this.addClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.hasFocus = false;
this.removeClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.ENTER_KEY = 13;
Spry.Widget.CollapsiblePanel.SPACE_KEY = 32;
Spry.Widget.CollapsiblePanel.prototype.onKeyDown = function(e)
{
var key = e.keyCode;
if (!this.hasFocus || (key != Spry.Widget.CollapsiblePanel.ENTER_KEY && key != Spry.Widget.CollapsiblePanel.SPACE_KEY))
return true;
if (this.isOpen())
this.close();
else
this.open();
if (e.stopPropagation)
e.stopPropagation();
if (e.preventDefault)
e.preventDefault();
return false;
};
Spry.Widget.CollapsiblePanel.prototype.attachPanelHandlers = function()
{
var tab = this.getTab();
if (!tab)
return;
var self = this;
Spry.Widget.CollapsiblePanel.addEventListener(tab, "click", function(e) { return self.onTabClick(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseover", function(e) { return self.onTabMouseOver(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseout", function(e) { return self.onTabMouseOut(); }, false);
if (this.enableKeyboardNavigation)
{
// XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
// rely on adding the tabindex attribute if it is missing to enable keyboard navigation
// by default.
// Find the first element within the tab container that has a tabindex or the first
// anchor tag.
var tabIndexEle = null;
var tabAnchorEle = null;
this.preorderTraversal(tab, function(node) {
if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
{
var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
if (tabIndexAttr)
{
tabIndexEle = node;
return true;
}
if (!tabAnchorEle && node.nodeName.toLowerCase() == "a")
tabAnchorEle = node;
}
return false;
});
if (tabIndexEle)
this.focusElement = tabIndexEle;
else if (tabAnchorEle)
this.focusElement = tabAnchorEle;
if (this.focusElement)
{
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "focus", function(e) { return self.onFocus(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "blur", function(e) { return self.onBlur(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "keydown", function(e) { return self.onKeyDown(e); }, false);
}
}
};
Spry.Widget.CollapsiblePanel.addEventListener = function(element, eventType, handler, capture)
{
try
{
if (element.addEventListener)
element.addEventListener(eventType, handler, capture);
else if (element.attachEvent)
element.attachEvent("on" + eventType, handler);
}
catch (e) {}
};
Spry.Widget.CollapsiblePanel.prototype.preorderTraversal = function(root, func)
{
var stopTraversal = false;
if (root)
{
stopTraversal = func(root);
if (root.hasChildNodes())
{
var child = root.firstChild;
while (!stopTraversal && child)
{
stopTraversal = this.preorderTraversal(child, func);
try { child = child.nextSibling; } catch (e) { child = null; }
}
}
}
return stopTraversal;
};
Spry.Widget.CollapsiblePanel.prototype.attachBehaviors = function()
{
var panel = this.element;
var tab = this.getTab();
var content = this.getContent();
if (this.contentIsOpen || this.hasClassName(panel, this.openClass))
{
this.removeClassName(panel, this.closedClass);
this.setDisplay(content, "block");
this.contentIsOpen = true;
}
else
{
this.removeClassName(panel, this.openClass);
this.addClassName(panel, this.closedClass);
this.setDisplay(content, "none");
this.contentIsOpen = false;
}
this.attachPanelHandlers();
};
Spry.Widget.CollapsiblePanel.prototype.getTab = function()
{
return this.getElementChildren(this.element)[0];
};
Spry.Widget.CollapsiblePanel.prototype.getContent = function()
{
return this.getElementChildren(this.element)[1];
};
Spry.Widget.CollapsiblePanel.prototype.isOpen = function()
{
return this.contentIsOpen;
};
Spry.Widget.CollapsiblePanel.prototype.getElementChildren = function(element)
{
var children = [];
var child = element.firstChild;
while (child)
{
if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
children.push(child);
child = child.nextSibling;
}
return children;
};
Spry.Widget.CollapsiblePanel.prototype.focus = function()
{
if (this.focusElement && this.focusElement.focus)
this.focusElement.focus();
};
/////////////////////////////////////////////////////
Spry.Widget.CollapsiblePanel.PanelAnimator = function(panel, doOpen, opts)
{
this.timer = null;
this.interval = 0;
this.stepCount = 0;
this.fps = 0;
this.steps = 10;
this.duration = 500;
this.onComplete = null;
this.panel = panel;
this.content = panel.getContent();
this.panelData = [];
this.doOpen = doOpen;
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
// If caller specified speed in terms of frames per second,
// convert them into steps.
if (this.fps > 0)
{
this.interval = Math.floor(1000 / this.fps);
this.steps = parseInt((this.duration + (this.interval - 1)) / this.interval);
}
else if (this.steps > 0)
this.interval = this.duration / this.steps;
var c = this.content;
var curHeight = c.offsetHeight ? c.offsetHeight : 0;
if (doOpen && c.style.display == "none")
this.fromHeight = 0;
else
this.fromHeight = curHeight;
if (!doOpen)
this.toHeight = 0;
else
{
if (c.style.display == "none")
{
// The content area is not displayed so in order to calculate the extent
// of the content inside it, we have to set its display to block.
c.style.visibility = "hidden";
c.style.display = "block";
}
// Unfortunately in Mozilla/Firefox, fetching the offsetHeight seems to cause
// the browser to synchronously re-layout and re-display content on the page,
// so we see a brief flash of content that is *after* the panel being positioned
// where it should when the panel is fully expanded. To get around this, we
// temporarily position the content area of the panel absolutely off-screen.
// This has the effect of taking the content out-of-flow, so nothing shifts around.
// var oldPos = c.style.position;
// var oldLeft = c.style.left;
// c.style.position = "absolute";
// c.style.left = "-2000em";
// Clear the height property so we can calculate
// the full height of the content we are going to show.
c.style.height = "";
this.toHeight = c.offsetHeight;
// Now restore the position and offset to what it was!
// c.style.position = oldPos;
// c.style.left = oldLeft;
}
this.increment = (this.toHeight - this.fromHeight) / this.steps;
this.overflow = c.style.overflow;
c.style.height = this.fromHeight + "px";
c.style.visibility = "visible";
c.style.overflow = "hidden";
c.style.display = "block";
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.start = function()
{
var self = this;
this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stop = function()
{
if (this.timer)
{
clearTimeout(this.timer);
// If we're killing the timer, restore the overflow
// properties on the panels we were animating!
if (this.stepCount < this.steps)
this.content.style.overflow = this.overflow;
}
this.timer = null;
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stepAnimation = function()
{
++this.stepCount;
this.animate();
if (this.stepCount < this.steps)
this.start();
else if (this.onComplete)
this.onComplete();
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.animate = function()
{
if (this.stepCount >= this.steps)
{
if (!this.doOpen)
this.content.style.display = "none";
this.content.style.overflow = this.overflow;
this.content.style.height = this.toHeight + "px";
}
else
{
this.fromHeight += this.increment;
this.content.style.height = this.fromHeight + "px";
}
};
My problem is that I want to close all other row when I click on any one.
change the "Spry.Widget.CollapsiblePanel.prototype.onBlur" section for this:
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false, { duration: this.duration, fps: this.fps, transition: this.transition });
this.animator.start();
}
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};

Categories