I'm trying to show a DIV to the user until he/she closes it. Once the user clicks close, the DIV remains close for 24 hours.
This is the working code that shows once every 24 hours. However, I'm not sure how to add the click function:
<?php
if (!isset($_COOKIE['cookie'])) {
setcookie('cookie', true, time() + 3600 * 24); // Save a cookie for 1 day
echo '<div class="slideshow"><span class="close">close</span>Hello World</div>';
}
?>
you should try something like this.
$(document).ready(function() {
// If the 'hide cookie is not set we show the message
if (!readCookie('hide')) {
$('#popupDiv').show();
}
// Add the event that closes the popup and sets the cookie that tells us to
// not show it again until one day has passed.
$('#close').click(function() {
$('#popupDiv').hide();
createCookie('hide', true, 1)
return false;
});
});
// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
code taken from here.SEE
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 a beginner and used jscript in my php page to hide/show table using the following code:
<script type="text/javascript">
function setTable(what){
if(document.getElementById(what).style.display=="none"){
document.getElementById(what).style.display="block";
}
else if(document.getElementById(what).style.display=="block"){
document.getElementById(what).style.display="none";
}
}
</script>
and display/hide table2 using:
<img src="/icons/index.png" width="55" height="55">
My problem is that while using this code, in case of any browser activity, the table is reset back to default state. I am struggling to enable users once they show/hide table it should continue even when refresh/or navigate happens within the pages. I know I should use cookies but have no idea. Please someone guide me.
thanks
Use cookies to store table state.
<script type="text/javascript">
var tableState = getCookie("table2state");
if (tableState != "") {
document.getElementById('table2').style.display = tableState;
}
function setTable(what) {
if (document.getElementById(what).style.display == "none") {
document.getElementById(what).style.display = "block";
setCookie(what + 'state', "block", 365);
} else if (document.getElementById(what).style.display == "block") {
document.getElementById(what).style.display = "none";
setCookie(what + 'state', "none", 365);
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
</script>
I am making a voting system for my theme
It is working fine in single.php
But when i keep it in index.php it only considers the id of first post and rest don't work
I think its not dealing with multiple post id
Here is the full code
Setting a cookie, calling Ajax action with jQuery
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$("#vote").not(".disabled").click(function() {
var el = $(this);
el.html('<span id="loader"></span>');
var nonce = $("input#voting_nonce").val();
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: '<?php echo $post->ID; ?>',
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = "<?php echo $post->ID; ?>";
} else {
var newcookie = cookie + ",<?php echo $post->ID; ?>";
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
This is what I put in my functions.php to register actions
add_action("wp_ajax_add_votes_options", "add_votes_options");
add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
function add_votes_options() {
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce'))
return;
$postid = $_POST['postid'];
$ip = $_POST['ip'];
$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
echo "null";
die(0);
} else {
$voter_ips[] = $ip;
update_post_meta($postid, "voter_ips", $voter_ips);
}
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;
die(0);
}
this is how I call my vote button and count button
<?php
// This will display "0 votes" and increase as votes are added
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
if($votes == 1) $plural = ""; else $plural = "s";
echo '<div id="votecounter">'.$votes.' vote'.$plural.'</div>';
?>
<?php
// This will display the vote button and disable it if a cookie has already
// been set. We also add the security nonce here.
$hasvoted = $_COOKIE['better_votes'];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' class="disabled"';
} else {
$vtext = "VOTE";
$class = "";
}
?>
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce', 'voting_nonce'); ?>
As for a beginning, you shouldn't have the same id for your button over and over again, so change this:
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
To this:
<?php
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' disabled';
} else {
$vtext = "VOTE";
$class = "";
}
<?php echo $vtext; ?>
This will result in id attribute of each vote button in the form of "vote-{post id}". And since I guess you still want to address all of your buttons in some way, you can now use the .vote-btn selector.
The problem with your JavaScript is that you pass the ID of the post to the script directly. This is fine, when you have only one post on the page, but when you have multiple posts, you have to either print your code multiple times, or get the post ID dynamically.
I prefer the second option, here's how your JS code should change in order to get that working:
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(".vote-btn").not(".disabled").click(function() {
var el = $(this),
nonce = $("input#voting_nonce", el.parent()).val(),
id = el.attr('id').replace(/vote-/, ''); // get the Post ID
el.html('<span id="loader"></span>');
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: id,
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = id;
} else {
var newcookie = cookie + "," + id;
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
So, in the above code, we get the ID of the post that the user is voting from, by replacing "vote-" with an empty string(so only the ID remains). Note also the following line:
nonce = $("input#voting_nonce", el.parent()).val(),
In this line, I assume that the nonce input as well as the button have the same parent(although you should be able to use the same nonce for all posts). You can also take your nonce one step further, by changing the code that generates it to:
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce-' . $post->ID, 'voting_nonce'); ?>
And change your add_votes_options function to:
$postid = $_POST['postid'];
if ( ! wp_verify_nonce( $_POST['nonce'], 'voting_nonce-' . $postid ) )
return;
This will bind each nonce to the ID of the post, that the nonce is for.
I think that's pretty much your problem. Please try my code and tell me if there are problems with it(if it's a JS error, please add message from the error console in FireBug, or WebKit's inspector).
PP: Just saw this:
Looking for an answer drawing from credible and/or official sources.
My answer was backed-up by my experience with WordPress and jQuery - and I earn my living by working mainly with WordPress(less jQuery, but I use it relatively often as well). Hope this will be enough :)
Is there any way to delete cookie until user will go to manually delete from the browser in PHP
Since cookies are stored on client side and browser send cookie in request header,
so if user delete cookie from browser then your script will not receive that cookie
and hence you need not to delete from server side in this particular scenario.
You can unset it:
<?php
unset($_COOKIE['myCookie']);
?>
or you can set a past time for it:
<?php
setcookie("myCookie", "", time() - 3600);
?>
In other words, you can delete a cookie only if your domain has set it.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
to delete the cookie you would do:
delete
Yes its
unset($_COOKIE['myCookie']);
I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>