I use TinyMCE for various projects. The problem I'm having ATM is that a lot of users copy&paste content form sources like Word or OpenOffice into the TinyMCE input. This results often in bloated code (e.g. things like <span lang="EN-GB"> being taken over from OpenOffice). TinyMCE's cleanup doesn't seem to remove those tags. Is there a way to strip all formating befor the text is pasted into the TinyMCE input area? Or is there another way to prevent such bloated code, for example by filtring it server side with PHP?
I know this is an opd question but for the benefit of others who may be searching for an answer to this (like I was!), TinyMCE now includes the ability to control what is pasted into the textbox.
In the init call, add the "paste" plugin and then set whatever options you require, e.g.
tinyMCE.init({
...
plugins: "paste",
paste_auto_cleanup_on_paste : true,
paste_remove_styles: true,
paste_remove_styles_if_webkit: true,
paste_strip_class_attributes: "all",
paste_remove_spans : true,
...
});
You can see all options in the tinyMCE wiki
I remove all tags using the followingc function on_preprocess:
strip_tags = function (str, allowed_tags) {
var key = '', allowed = false;
var matches = []; var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};
// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}
str += '';
// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);
// Go through all HTML tags
for (key in matches) {
if (isNaN(key)) {
// IE7 Hack
continue; }
// Save HTML tag
html = matches[key].toString();
// Is tag not in allowed list? Remove from str!
allowed = false;
// Go through all allowed tags
for (k in allowed_array) { // Init
allowed_tag = allowed_array[k];
i = -1;
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag) ;}
// Determine
if (i == 0) { allowed = true;
break;
}
}
if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}
return str;
};
In the tinymce init i place
paste_preprocess : function(pl, o) {
// remove Clipboard header on MAC
var pos_sel = o.content.search("EndSelection:");
var pos_fra = o.content.search("EndFragment:");
var mac_header_found = false;
if (o.content.search("Version:") == 0 && pos_sel < 135 && pos_sel > 120){
o.content = o.content.substring(pos_sel+23);
mac_header_found = true;
}
else if (o.content.search("Version:") == 0 && pos_fra < 80 && pos_fra > 75){
o.content = o.content.substring(pos_fra+23);
mac_header_found = true;
}
// Copy from Word oder OpenOffice (MAC) - remove header
if (o.wordContent || mac_header_found) {
// first style tag + content to be removed
var pos_start_style = o.content.search('<style');
var pos_end_style = o.content.search('</style>');
if (pos_start_style > 0 && pos_end_style > pos_start_style) {
o.content = o.content.substring(0, pos_start_style).concat(o.content.substring(pos_end_style + 8));
}
// complete Worddokument gets pasted
else {
var pos_start_p = o.content.search('<p');
if (pos_start_p) o.content = o.content.substring(pos_start_p);
}
}
o.content = ir.im.strip_tags( o.content, '' );
// NO-Break Zero-width space if empty
if (o.content == '') {
o.content = '';
}
},
Related
I am a student who will conduct an experiment online.
The participants go to a website (a more complex version of this one: http://auforskning.rf.gd/TEST2.php) which will track a) which buttons they press and b) how long time the buttons are pushed. This is to track how many seconds each participant spend on reading the information.
However, there is one problem: The participants have to press 'Submit' or 'Next' in order to store the informations. If they read the information behind the boxes (as intended) and just close the window, the data will be lost.
Is there a way to store data continuously, so that the data isn't lost if they just close the window?
mlweb.js-file:
dtNewDate = new Date();
starttime = dtNewDate.getTime(); // abs. starttime of experiment
// set vars for delay
prevtime = 0; // memory in timefunction to compensate for delay
dtime=0;
prevCell = -1; // delay lag memory (-1 means first cell is not delayable
loaded = false; // flag to test whether page has been loaded 9is set to true in reorder
boxOpen = false; // flag to test whether box is already open (using in showCont and hideCont)
chkFrm = false // flag to test whether additional form elements have to be checked on submission
warningTxt = "Some questions have not been answered. Please answer all questions before continuing!";
CBpreset = false; // flag to set CB order fixed by a matrix on forehand: default is set to false
prevfieldname = ""; // default for switching clicks
transpImg = new Image()
tempImg = new Image()
previousSrc="";
// default values
mlweb_outtype="XML";
mlweb_fname=0;
masterCond = 1; // number of master conditions
randomOrder = false; // force randomize of counterbalancing order
subject="";
evtOpen = 0;
evtClose = 0;
tmDirectStart = false;
tmTimeUp = false;
tmActive = false;
tmCurTime = 0;
// get source transparant image
transpImg.src="transp.gif"
function abc_num(str)
{
out=str.toUpperCase().charCodeAt(0)-65;
return out
}
function fac(x)
{
// Faculty: x!=x(x-1)...1
var outp=1;
for (var i=1; i<=x; i++)
{outp=outp*i}
return outp
}
function CountBal(subjnr, num)
{
// counterbalance based on subj number.
// first subject is 0
// Num is number of options to counterbalance
// (number of orders is Num!)
var numOrd=fac(num);
start = subjnr - numOrd*Math.floor((subjnr-1)/numOrd)
orderstr=""
for (var i=0;i<num;i++)
{orderstr+=i.toString()}
outstr=""
for (var i=num; i>0; i--)
{
var den=fac(i-1);
pos = Math.floor((start-1)/den)+1
outstr+=orderstr.charAt(pos-1)+","
orderstr = orderstr.substring(0,pos-1)+orderstr.substr(pos)
start=start-(pos-1)*den
}
outstr=outstr.substr(0,outstr.length-1)
return outstr.split(",")
}
function ExpMatrix(M)
{ // expand data matrices
var Mrows=M.split("`");
var outM = new Array();
for (rowcount=0;rowcount<Mrows.length;rowcount++)
{
outM[rowcount]=Mrows[rowcount].split("^")
}
return outM;
}
function ExpRow(M)
{ // expand data vectors
var outM = new Array();
outM = M.split("^")
return outM;
}
function btnHover(loc,act)
{
if (act=='out')
{
if (loc.className.indexOf(" ")>0) {tempstyle= loc.className.substring(0,loc.className.indexOf(" "));}
}
else
{tempstyle=loc.className + ' btnhov';}
loc.className=tempstyle;
}
function timefunction(event,name,value) {
// Record proc data in form element
mlweb_form=document.forms[mlweb_fname].elements['procdata']
dtNewDate = new Date();
eventtime = dtNewDate.getTime();
var curtime = eventtime-starttime-dtime; // dtime is to compensate for delay time (failed openings have negative time!
// if (prevtime>curtime) {curtime=prevtime;} else {prevtime=curtime}; // check with previous event time: if smaller, then delay was not finished: set curtime to prevtime so event has duration 0;
dtime=0; // reset dtime
if (mlweb_outtype=="XML")
{
var str="<eventblock><event>"+event+"</event><name>"+name+"</name><value>"+value+"</value><time>"+curtime+"</time></eventblock>";
var headerstr="<?xml version=1.0?>"
}
else
{
var str="\""+event+"\",\""+name+"\",\""+value+"\",\""+curtime+"\"\n"
var headerstr="\"event\",\"name\",\"value\",\"time\"\n"
};
if(mlweb_form.value=='')
{
mlweb_form.value=headerstr;
}
mlweb_form.value+=str;
if (event=="onload") {reorder();}
return true;
}
// convert event to eventdata and call save function
function RecordEventData(objActionElement, objEvent)
{
var strName, strEventType, strFormValue;
strName = objActionElement.name;
strFormValue = (objActionElement.value) ? objActionElement.value : "";
strEventType = objEvent.type;
//call timefunction
timefunction(strEventType,strName, strFormValue)
return false;
}
function checkForm(formHandle)
{
if (chkFrm)
{
noElm = document.forms[mlweb_fname].elements.length;
var filled=true;
for (i=0;i<noElm;i++)
{
elemHandle = document.forms[0].elements[i];
if (elemHandle.type=="hidden") {continue};
if (elemHandle.value=="") {filled = false; break};
if (elemHandle.type=="select-one") {if (elemHandle.options[elemHandle.selectedIndex].value=="") {filled = false; break};}
if (elemHandle.type=="radio") // procedure to check radio buttons
{
radio_name=elemHandle.name; // get name (needed to retrieve length)
// get length of radio button group
r_length = eval("document.forms[0]."+radio_name).length
for (ri=0;ri<r_length;ri++) // check each button and break loop if checked button was found
{ radioHandle = document.forms[0].elements[i+ri];
if (radioHandle.checked) {filled=true; break} else {filled=false};
}
if (filled) {i=i+r_length-1; continue} else {break}; // if checked button found; continue
// else break loop and show warning
}
}
if (!filled) {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
if ((chkchoice=="nobuttons") | !chkFrm) {return true;}
if (chkchoice==true) {timefunction('submit','submit','succeeded');return true} else {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
function objElem(name,value)
{
this.name=name
this.value=value
}
function ShowCont(fieldname, objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurs. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem = new objElem
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (boxOpen) {return;}
if (evtClose<3) {boxOpen = true;} //set flag to show box is open
// retrieve tagname and txt for this cell
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
}
function HideCont(fieldname,objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!boxOpen) {return;} // do not close boxes that are not open...
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
boxOpen = false; // set tag to show that box is closed again
thisElem = new objElem;
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
function SwitchCont(fieldname, objEvent)
{
// special function for clicking tasks
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurred. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
thisElem = new objElem
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (fieldname==prevfieldname)
{
// just close current box if box is same as previous
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
prevfieldname="";
}
else
{
if ((prevfieldname!="")&(evtClose==1))
{
// first close prev box if box is not same as previous
window.clearTimeout(delay);
var row = abc_num(prevfieldname);
var col = parseInt(prevfieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(prevfieldname+"_txt");
HandleBox = document.getElementById(prevfieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+prevfieldname+"_txt"+"']");
HandleBox=eval("document.all['"+prevfieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
if ((prevfieldname=="")|(evtClose==1))
{
// only if any box may be opened or there as no previous box open, show content
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
prevfieldname=fieldname;
}
}
}
function recChoice(eventname ,name, value)
{
chkchoice = true;
timefunction(eventname, name, value);
if (document.forms[mlweb_fname].choice) {document.forms[mlweb_fname].choice.value = name;}
if (btnType=="button")
{
for (i=0;i<btnTxt.length;i++)
{
if (btnFlg==1) {btnNum = ColOut[i]} else {btnNum = RowOut[i]};
HandleBut = eval("document.forms['"+mlweb_fname+"']."+btnTag[btnNum]);
if (btnTag[btnNum]==name) {HandlePressed = HandleBut};
if (btnState[btnNum]=="1") {HandleBut.className = 'btnStyle';}
}
HandlePressed.className='pressedStyle btnHov';
}
}
function loadMatrices()
{
// get settings data from script in body
txtcont = ExpMatrix(txt);
statecont = ExpMatrix(state);
tagcont = ExpMatrix(tag);
boxcont = ExpMatrix(box);
WidthCol = ExpRow(W_Col);
HeightRow = ExpRow(H_Row);
DTimes = ExpMatrix(delay);
CountCol = ExpRow(CBCol);
CountRow = ExpRow(CBRow);
btnTxt = ExpRow(btntxt);
btnTag = ExpRow(btntag);
btnState = ExpRow(btnstate);
// new in version 99.2: CB preset matrix
if (CBpreset) {
CBorder = ExpMatrix(CBord);
}
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{ColOut[i]=i;}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{RowOut[i]=i;}
Dlist = new Array();
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
}
}
}
function reorder()
{
// if referer present (or other php/asp code) then get current hit number
if (document.cookie.indexOf("mlweb_subject=")!=-1)
{
subjstr=document.cookie;
subject=subjstr.substr(subjstr.indexOf("mlweb_subject=")+14);
}
if (document.cookie.indexOf("mlweb_condnum=")!=-1)
{
subjstr=document.cookie;
subjnr=parseInt(subjstr.substr(subjstr.indexOf("mlweb_condnum=")+14));
subjtype = "cookie";
//alert(subjnr + " " + subjtype);
}
else
{
if (typeof ref_cur_hit!="undefined")
{subjnr = ref_cur_hit; subjtype = "header"}
else
{
subjnr=-1; subjtype = "random";
}
}
// if subj nr turns out to be not a number, or randomizer is set to true then set it to randomize
if (isNaN(subjnr)|randomOrder) {subjnr=-1; subjtype = "random";}
if (document.forms[mlweb_fname].condnum) {document.forms[mlweb_fname].condnum.value = subjnr;}
if (document.forms[mlweb_fname].expname) {document.forms[mlweb_fname].expname.value = expname;}
if (document.forms[mlweb_fname].nextURL) {document.forms[mlweb_fname].nextURL.value = nextURL;}
if (document.forms[mlweb_fname].subject) {document.forms[mlweb_fname].subject.value = subject;}
if (document.forms[mlweb_fname].to_email) {document.forms[mlweb_fname].to_email.value = to_email;}
if (CBpreset)
{
if (subjnr==-1) {subjnr=Math.floor(Math.random()*CBorder.length)}
// CB order is preset in a matrix
curord = Math.floor(subjnr/masterCond) % CBorder.length;
cbcount=0;
for (var i=0; i<CountCol.length; i++)
{
ColOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++;
}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
RowOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++
}
}
else
{
// code if no prespecified CBorder
// retrieve position of counterbalance groups
var cf=new Array() // position of fixed cols
var c1=new Array() // position of c1 cols
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': cf[cf.length]=i;break;
case '1': c1[c1.length]=i;break;
}
}
var rf=new Array() // position of fixed rows
var r1=new Array() // position of c1 rows
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': rf[rf.length]=i;break;
case '1': r1[r1.length]=i;break;
}
}
// subjDen is the denominator used to devide the subj number for each counterbalance step
subjDen = 1;
if (subjtype!="random") {subjDen = Math.floor(subjDen * masterCond)};
// first determine column and row connects and switch on that
var numCond = (c1.length>0 ? fac(c1.length) : 1)*(r1.length>0 ? fac(r1.length) : 1);
if (subjnr==-1) {subjnr=Math.floor(Math.random()*numCond)}
//alert("total cond:" + numCond+"\nsubject: "+subjnr);
// counterbalance col groups
if (c1.length>0) {c1_order=CountBal(subjnr/subjDen+1,c1.length);
subjDen = subjDen*fac(c1.length);}
var c1count=0;
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': ColOut[i]=i;break;
case '1': ColOut[i]=c1[c1_order[c1count]];c1count++;break;
}
}
// counterbalance rows
if (r1.length>0) {r1_order=CountBal(subjnr/subjDen+1,r1.length); subjDen = subjDen * fac(r1.length);}
var r1count=0;
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': RowOut[i]=i;break;
case '1': RowOut[i]=r1[r1_order[r1count]];r1count++;break;
}
}
}
Dlist=new Array();
// reorder and resize table content
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
var label = String.fromCharCode(j+97)+i.toString();
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleCont = document.getElementById(label+"_cont");
HandleTxt = document.getElementById(label+"_txt");
HandleBox = document.getElementById(label+"_box");
HandleTD = document.getElementById(label+"_td");
HandleTDbox = document.getElementById(label+"_tdbox");
HandleImgBox = document.getElementById(label+"_img");
HandleImg = eval("document.images."+label);
pxstr="px";
}
else if (document.all)
{
//IE4/5
HandleCont=eval("document.all['"+label+"_cont"+"']");
HandleTxt=eval("document.all['"+label+"_txt"+"']");
HandleTD=eval("document.all['"+label+"_td"+"']");
HandleBox=eval("document.all['"+label+"_box"+"']");
HandleTDbox=eval("document.all['"+label+"_tdbox"+"']");
HandleImgbox=eval("document.all['"+label+"_img"+"']");
HandleImg = eval("document.images."+label);
pxstr="px";
}
// set txt
HandleTD.innerHTML =""; // empty for IE5 on mac bug
// if txtcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (txtcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTD.innerHTML = " "}
else {
// if boxes are non-active and labels are fixed, header rows should also be fixed
if (statecont[RowOut[j]][ColOut[i]]=="0")
{
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTD.innerHTML = txtcont[temprow][tempcol];
}
else {HandleTD.innerHTML = txtcont[RowOut[j]][ColOut[i]]};
};
HandleTDbox.innerHTML =""; // empty for IE5 on mac bug
// if boxcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (boxcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTDbox.innerHTML = " "}
else {
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTDbox.innerHTML = boxcont[temprow][tempcol];
};
//set sizes
HandleTD.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTD.height = parseInt(HeightRow[RowOut[j]])-5;
HandleTDbox.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTDbox.height = parseInt(HeightRow[RowOut[j]])-5;
if (statecont[RowOut[j]][ColOut[i]]=="1") {HandleTD.className = activeClass;} else {HandleTD.className = inactiveClass};
HandleCont.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleCont.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleTxt.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.clip = "rect(0px "+ HandleTxt.style.width + " " + HandleTxt.style.height +" 0px)";
HandleBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleBox.style.clip = "rect(0px "+ HandleBox.style.width + " " + HandleBox.style.height +" 0px)";
HandleImgBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleImgBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleImg.height = parseInt(HeightRow[RowOut[j]]);
HandleImg.width = parseInt(WidthCol[ColOut[i]]);
// open state=0 boxes using img names from imgcont matrix
if (statecont[RowOut[j]][ColOut[i]] == '0') {HandleBox.style.visibility = "hidden"; HandleTxt.style.visibility = "visible";} else {HandleBox.style.visibility = "visible"; HandleTxt.style.visibility = "hidden";}
}
}
// if there are buttons then reorder the buttons according to the counterbalancing scheme
if (btnFlg>0)
{
btn_inner = new Array()
for (bc=0;bc<btnTxt.length;bc++)
{
// swap names if not counterbalancing is turned off
if (btnFlg==1)
{
//var btnNum = parseInt(ColOut[bc])
realNum=parseInt(ColOut[bc]);
if (colFix) {var txtNum = bc; }
else {var txtNum = realNum;}
}
else {
//var btnNum = parseInt(RowOut[bc])
realNum=parseInt(RowOut[bc]);
if (rowFix) {var txtNum = bc;}
else {var txtNum = realNum;}
}
if (btnState[realNum]=="1")
{
if (btnType=="radio")
{var functionstr = "onMouseOver=\"timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT type=\"radio\" name=\"mlchoice\" value=\""+btnTag[realNum]+"\" "+functionstr+">"+btnTxt[txtNum];}
else
{var functionstr = "onMouseOver=\"btnHover(this,'in');timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"btnHover(this,'out');timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT class=\"btnStyle\" type=\"button\" name=\"" + btnTag[realNum] + "\" value=\""+btnTxt[txtNum]+"\" "+functionstr+">";}
}
else
{btn_inner[bc]=" ";}
}
for (bc=0;bc<btnTxt.length;bc++)
{
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTD = document.getElementById("btn_"+bc.toString());
}
else if (document.all)
{
//IE4/5
HandleTD=eval("document.all['"+"btn_"+bc.toString()+"']");
}
if (bc==0) {defTDcolor = HandleTD.style.backgroundColor;}
docstr=btn_inner[bc];
HandleTD.innerHTML =""; // empty for IE5 on mac bug
HandleTD.innerHTML = docstr;
}
}
// send col and row orders as events
timefunction("subject", subjtype,subjnr)
timefunction("order","col",ColOut.join("_"))
timefunction("order","row",RowOut.join("_"))
timefunction("events","open_close",evtOpen.toString()+"_"+evtClose.toString());
loaded = true; // set flag that page has been loaded;
if (tmActive) {
initTmBar();
if (tmDirectStart) {startTmBar();}
}
return;
}
function initTmBar() {
if (!tmActive) {return false;}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTmCont = document.getElementById("tmCont");
HandleTmBar = document.getElementById("tmBar");
HandleTmTime = document.getElementById("tmTime");
}
else if (document.all)
{
//IE4/5
HandleTmCont =eval("document.all['tmCont']");
HandleTmBar=eval("document.all['tmBar']");
HandleTmTime=eval("document.all['tmTime']");
}
HandleTmCont.style.width=parseInt(tmWidthPx+4)+"px";
HandleTmTime.style.width=parseInt(tmWidthPx+4)+"px";
if (tmFill) {HandleTmBar.style.width="0px"; HandleTmTime.innerHTML="0 sec";}
else {HandleTmBar.style.width=parseInt(tmWidthPx)+"px"; HandleTmTime.innerHTML=parseInt(tmTotalSec)+" sec";}
if (tmShowTime) {HandleTmTime.style.visibility="visible";}
else {HandleTmTime.style.visibility="hidden";}
}
function startTmBar()
{
if (!tmActive) {return false;}
tmCurTime = 0;
tmInt = setInterval("refreshTmBar()", tmStepSec*1000);
}
function refreshTmBar()
{
if (!tmActive) {return false;}
tmCurTime= tmCurTime + tmStepSec*1000;
if (tmCurTime>tmTotalSec*1000) {clearInterval(tmInt); tmTimeUp=true; return;}
if (tmFill) {
HandleTmBar.style.width=parseInt(Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
if (tmMinLabel=="false" | tmCurTime <60000) {HandleTmTime.innerHTML=parseInt(Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var mnt = parseInt(Math.floor(tmCurTime/60000));
var secs = parseInt((tmCurTime-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
else {HandleTmBar.style.width=parseInt(tmWidthPx-Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" sec";
if (tmMinLabel=="false" | tmCurTime<60000) {HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var timeleft = tmTotalSec*1000-tmCurTime;
var mnt = parseInt(Math.floor(timeleft/60000));
var secs = parseInt((timeleft-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
}
EDIT: There is a lot going on in that javascript function. A lot of it is exporting and importing values from and to the form. Without
really knuckling down into it, I can't be certain that my attempts
below won't ruin the integrity of your data.
Please consider hiring someone to correct this. It may be a relativeley simple change and a google of 'freelance javascript
developer' would help you find someone.
That code submits the words 'submit','submit','submit' to a function called timefunction. Apart from the hint that this code is a form of subliminal messaging to make your uses more subservient (/joke), it looks like that function is defined elsewhere. This means we cannot tell what it actually does. mlweb.js is an external javascript file that is linked at the start of this page, and that leads me to believe it is where that function is defined (that means all the code to handle that function comes from there).
There is, however, and obvious link from your submit button that calls the function using an onclick method. onClick=timefunction('submit','submit','submit') which could be replicated based on other criteria that doesn't require a click.
If, for example, you wished to make it submit the data IF someone tries to leave the page (this may cause an issue if they submit first.)
Rough code
window.onbeforeunload = timefunction('submit','submit','submit');
This code would tell the browser to send this function those three words before closing.
As that code seems to simply send text values (probably to hint timefunction to do some action in particular), there may be one of those values you could change to record that it was a close event rather than a submit. But we do not know which one without seeing the other code. I would experiment by changing one at a time if it was my code. But I would not advise you to do so since you don't know what the rest does.
Then you have an action on the form that does two things, one is onSubmit="return checkForm(this)" which seems like a form validator to make sure everything is filled in correctly. You could add this step in to ensure it has, but now you're going to try and prevent them from closing the window, and bug them about not submitting it.
Then the form is actually submitted to save.php which we also cannot see. Again, we can send the form details (as is) just as if it was submitted (WITHOUT VALIDATION). We would do that by adding document.forms["mlwebform"].submit(); with the previous code.
We can squeeze in the form validation, but I'm not sure what the return result is. Here's two options.
Like so
//no validation!!!
window.onbeforeunload = function() {
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
}
//with possible validation
window.onbeforeunload = function() {
if (checkForm(document.forms["mlwebform"])) { //if the validator returns true, continue
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
} else { //if the validator does anything else, say so
MsgBox("Apologies, something went wrong");
}
}
This COULD work, depending on the functions in that other file. I would try the second one first, because having validation would be great. Otherwise use the first one as a fall back.
I would add this after loadMatrices(); and before </script>.
Conclusion
Seeing mlweb.js would help.
We can try and fake the same response a submit would do (this could cause errors, and we don't know how they are dealt with)
If you're brave, and there are no/little consequences to you messing up your data by dumping errors and un-validated into it through experimentation at this stage, then test out the 2 code examples above.
If the integrity of your data at this stage is important, or this is a live/production site, then don't! Get someone to properly assess the code
I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.
I have got a JavaScript here that is suppose to make an image (ghost) appear on screen, fly around for a bit, and then fade out before repeating again later on. The script works just fine without a DOCTYPE in my document, however if I add any DOCTYPEs, only the appear/disappear works. For some reason it doesn't move around on screen. The DOCTYPE I need to use is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This has been driving me crazy and I can't seem to figure out how to make it compatible. I just need to get the movement portion working with a DOCTYPE. Any help with this would really be appreciated. Below is the script:
if(!window.JSFX) JSFX=new Object();
JSFX.ghostImages = new Array(
"<img src='/ghost.png'>",
"<img src='/ghost2.png'>"
);
var ns4 = document.layers;
var ie4 = document.all;
JSFX.makeLayer = function(id)
{
var el = document.getElementById ? document.getElementById(id) :
document.all ? document.all[id] :
document.layers[id];
if(ns4) el.style=el;
el.sP=function(x,y){this.style.right = x;this.style.top=y;};
el.show=function(){ this.style.visibility = "visible"; }
el.hide=function(){ this.style.visibility = "hidden"; }
if(ns4 || window.opera)
el.sO = function(pc){return 0;};
else if(ie4)
el.sO = function(pc)
{
if(this.style.filter=="")
this.style.filter="alpha(opacity=100);";
this.filters.alpha.opacity=pc;
}
else
el.sO = function(pc)
{
this.style.opacity=pc/100;
}
return el;
}
if(window.innerWidth)
{
gX=function(){return innerWidth;};
gY=function(){return innerHeight;};
}
else
{
gX=function(){return document.body.width-50;};
gY=function(){return document.body.height-50;};
}
JSFX.ghostOutput=function()
{
for(var i=0 ; i<JSFX.ghostImages.length ; i++)
document.write(ns4 ? "<LAYER NAME='gh"+i+"'>"+JSFX.ghostImages[i]+"<\/LAYER>" :
"<DIV id='gh"+i+"' style='position:absolute'>"+JSFX.ghostImages[i]+"<\/DIV>" );
}
JSFX.ghostSprites = new Array();
JSFX.ghostStartAni = function()
{
for(var i=0 ;i<JSFX.ghostImages.length;i++)
{
var el=JSFX.makeLayer("gh"+i);
el.x=Math.random()*gX();
el.y=Math.random()*gY();
el.tx=Math.random()*gX();
el.ty=Math.random()*gY();
el.dx=-5+Math.random()*10;
el.dy=-5+Math.random()*10;
el.state="off";
el.op=0;
el.sO(el.op);
el.hide();
JSFX.ghostSprites[i] = el;
}
setInterval("JSFX.ghostAni()", 40);
}
JSFX.ghostAni = function()
{
for(var i=0 ;i<JSFX.ghostSprites.length;i++)
{
el=JSFX.ghostSprites[i];
if(el.state == "off")
{
if(Math.random() > .99)
{
el.state="up";
el.show();
}
}
else if(el.state == "on")
{
if(Math.random() > .98)
el.state="down";
}
else if(el.state == "up")
{
el.op += 2;
el.sO(el.op);
if(el.op==100)
el.state = "on";
}
else if(el.state == "down")
{
el.op -= 2;
if(el.op==0)
{
el.hide();
el.state = "off";
}
else
el.sO(el.op);
}
var X = (el.tx - el.x);
var Y = (el.ty - el.y);
var len = Math.sqrt(X*X+Y*Y);
if(len < 1) len = 1;
var dx = 20 * (X/len);
var dy = 20 * (Y/len);
var ddx = (dx - el.dx)/10;
var ddy = (dy - el.dy)/10;
el.dx += ddx;
el.dy += ddy;
el.sP(el.x+=el.dx,el.y+=el.dy);
if(Math.random() >.95 )
{
el.tx = Math.random()*gX();
el.ty = Math.random()*gY();
}
}
}
JSFX.ghostStart = function()
{
if(JSFX.ghostLoad)JSFX.ghostLoad();
JSFX.ghostStartAni();
}
JSFX.ghostOutput();
JSFX.ghostLoad=window.onload;
window.onload=JSFX.ghostStart;
Here is an example of the script on a page without a DOCTYPE:
http://boomansion.net/test.php
...and an exmaple on a page with a DOCTYPE (look at the very bottom):
http://boomansion.net/test2.php
Thanks in advance!
You set setting top and left to Numbers, but they take lengths (and non-zero lengths must have a unit).
When you add a Doctype, browsers:
Assume you know what you are doing
Follow the specification more closely
(Consequently) are more consistent with each other
(Consequently) will treat more errors are "values to ignore" instead of "values to fix up automatically".
You probably want to + "px".
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.
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!