JavaScript - Help Editing My Animated Div Javascript -- Stop It Remembering The Last Active Div
I'm using some free javascript for my website and I'm trying to edit it slightly to behave the way I want on my site. Right now it works fine apart from one thing... It remembers the last active div that was open... then when you visit the site again or refresh the page... that div stays open and doesn't close when toggling the other animated divs like it is supposed to.
How would I remove the last active div function or get it to close again when toggling other animated divs.. Thanks so much if you can help Here is the site: www.gjoob.terryarchonship.com here is where the last active div java is Code: showhide:function(divid, action){ var $divref=this.divholders[divid].$divref //reference collapsible DIV if (this.divholders[divid] && $divref.length==1){ //if DIV exists var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any) if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid) //if last active DIV is set this.slideengine(targetgroup.lastactivedivid, 'hide') //hide last active DIV within group first this.slideengine(divid, 'show') targetgroup.lastactivedivid=divid //remember last active DIV } else{ this.slideengine(divid, action) } } } here is the entire javascript: Code: var animatedcollapse={ divholders: {}, //structu {div.id, div.attrs, div.$divref, div.$togglerimage} divgroups: {}, //structu {groupname.count, groupname.lastactivedivid} lastactiveingroup: {}, //structu {lastactivediv.id} preloadimages: [], show:function(divids){ //public method if (typeof divids=="object"){ for (var i=0; i<divids.length; i++) this.showhide(divids[i], "show") } else this.showhide(divids, "show") }, hide:function(divids){ //public method if (typeof divids=="object"){ for (var i=0; i<divids.length; i++) this.showhide(divids[i], "hide") } else this.showhide(divids, "hide") }, toggle:function(divid){ //public method if (typeof divid=="object") divid=divid[0] this.showhide(divid, "toggle") }, addDiv:function(divid, attrstring){ //public function this.divholders[divid]=({id: divid, $divref: null, attrs: attrstring}) this.divholders[divid].getAttr=function(name){ //assign getAttr() function to each divholder object var attr=new RegExp(name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,) return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null //return value portion (string), or 0 (false) if none found } this.currentid=divid //keep track of current div object being manipulated (in the event of chaining) return this }, showhide:function(divid, action){ var $divref=this.divholders[divid].$divref //reference collapsible DIV if (this.divholders[divid] && $divref.length==1){ //if DIV exists var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any) if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid) //if last active DIV is set this.slideengine(targetgroup.lastactivedivid, 'hide') //hide last active DIV within group first this.slideengine(divid, 'show') targetgroup.lastactivedivid=divid //remember last active DIV } else{ this.slideengine(divid, action) } } }, slideengine:function(divid, action){ var $divref=this.divholders[divid].$divref var $togglerimage=this.divholders[divid].$togglerimage if (this.divholders[divid] && $divref.length==1){ //if this DIV exists var animateSetting={height: action} if ($divref.attr('fade')) animateSetting.opacity=action $divref.animate(animateSetting, $divref.attr('speed')? parseInt($divref.attr('speed')) : 500, function(){ if ($togglerimage){ $togglerimage.attr('src', ($divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open) } if (animatedcollapse.ontoggle){ try{ animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display')) } catch(e){ alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.") } } }) return false } }, generatemap:function(){ var map={} for (var i=0; i<arguments.length; i++){ if (arguments[i][1]!=null){ //do not generate name/value pair if value is null map[arguments[i][0]]=arguments[i][1] } } return map }, init:function(){ var ac=this jQuery(document).ready(function($){ animatedcollapse.ontoggle=animatedcollapse.ontoggle || null var urlparamopenids=animatedcollapse.urlparamselect() //Get div ids that should be expanded based on the url (['div1','div2',etc]) var persistopenids=ac.getCookie('acopendivids') //Get list of div ids that should be expanded due to persistence ('div1,div2,etc') var groupswithpersist=ac.getCookie('acgroupswithpersist') //Get list of group names that have 1 or more divs with "persist" attribute defined if (persistopenids!=null) //if cookie isn't null (is null if first time page loads, and cookie hasnt been set yet) persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',') //if no divs are persisted, set to empty array, else, array of div ids groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',') //Get list of groups with divs that are persisted jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object this.$divref=$('#'+this.id) if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){ //if this div carries a user "persist" setting, or belong to a group with at least one div that does var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none' } else{ var cssdisplay=this.getAttr('hide')? 'none' : null } if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains the single array element "all", or this div's ID cssdisplay='block' //set div to "block", overriding any other setting } else if (urlparamopenids[0]=="none"){ cssdisplay='none' //set div to "none", overriding any other setting } this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay])) this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')])) if (this.getAttr('group')){ //if this DIV has the "group" attr defined var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={}) //Get settings for this group, or if it no settings exist yet, create blank object to store them in targetgroup.count=(targetgroup.count||0)+1 //count # of DIVs within this group if (jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains this div's ID targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded). Overrides other settings targetgroup.overridepersist=1 //Indicate to override persisted div that would have been expanded } } }) //end divholders.each jQuery.each(ac.divgroups, function(){ //loop through each group if (this.lastactivedivid && urlparamopenids[0]!="none") //show last "active" DIV within each group (one that should be expanded), unless url param="none" ac.divholders[this.lastactivedivid].$divref.show() }) if (animatedcollapse.ontoggle){ jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object and fire ontoggle event animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display')) }) } //Parse page for links containing rel attribute var $allcontrols=$('a[rel]').filter('[rel^="collapse["], [rel^="expand["], [rel^="toggle["]') //get all elements on page with rel="collapse[]", "expand[]" and "toggle[]" $allcontrols.each(function(){ //loop though each control link this._divids=this.getAttribute('rel').replace(/(^\w+)|(\s+)/g, "").replace(/[\[\]']/g, "") //cache value 'div1,div2,etc' within identifier[div1,div2,etc] if (this.getElementsByTagName('img').length==1 && ac.divholders[this._divids]){ //if control is an image link that toggles a single DIV (must be one to one to update status image) animatedcollapse.preloadimage(this.getAttribute('data-openimage'), this.getAttribute('data-closedimage')) //preload control images (if defined) $togglerimage=$(this).find('img').eq(0).data('srcs', {open:this.getAttribute('data-openimage'), closed:this.getAttribute('data-closedimage')}) //remember open and closed images' paths ac.divholders[this._divids].$togglerimage=$(this).find('img').eq(0) //save reference to toggler image (to be updated inside slideengine() ac.divholders[this._divids].$togglerimage.attr('src', (ac.divholders[this._divids].$divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open) } $(this).click(function(){ //assign click behavior to each control link var relattr=this.getAttribute('rel') var divids=(this._divids=="")? [] : this._divids.split(',') //convert 'div1,div2,etc' to array if (divids.length>0){ animatedcollapse[/expand/i.test(relattr)? 'show' : /collapse/i.test(relattr)? 'hide' : 'toggle'](divids) //call corresponding public function return false } }) //end control.click })// end control.each $(window).bind('unload', function(){ ac.uninit() }) }) //end doc.ready() }, uninit:function(){ var opendivids='', groupswithpersist='' jQuery.each(this.divholders, function(){ if (this.$divref.css('display')!='none'){ opendivids+=this.id+',' //store ids of DIVs that are expanded when page unloads: 'div1,div2,etc' } if (this.getAttr('group') && this.getAttr('persist')) groupswithpersist+=this.getAttr('group')+',' //store groups with which at least one DIV has persistance enabled: 'group1,group2,etc' }) opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '') groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '') this.setCookie('acopendivids', opendivids) this.setCookie('acgroupswithpersist', groupswithpersist) }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value, days){ if (typeof days!="undefined"){ //if set persistent cookie var expireDate = new Date() expireDate.setDate(expireDate.getDate()+days) document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString() } else //else if this is a session only cookie document.cookie = name+"="+value+"; path=/" }, urlparamselect:function(){ window.location.search.match(/expanddiv=([\w\-_,]+)/i) //search for expanddiv=divid or divid1,divid2,etc return (RegExp.$1!="")? RegExp.$1.split(",") : [] }, preloadimage:function(){ var preloadimages=this.preloadimages for (var i=0; i<arguments.length; i++){ if (arguments[i] && arguments[i].length>0){ preloadimages[preloadimages.length]=new Image() preloadimages[preloadimages.length-1].src=arguments[i] } } } } Similar TutorialsHi I am trying to include an animated banner on my website but it wont work is there anyone out there who can look at my code and tell me where I am going wrong? Code: <head> <title>Online movie store</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" language="JavaScript" src="mylibrary.js"> </script> <script type="text/javascript" language="JavaScript"> <!-- var myproducts = new Array("sherlockholmes","anchorman","weweresoldiers","starshiproopers","homealone","gamer","residentevil"); var itemqty = 0; function showCookies(){ for (i=0;i<myproducts.length;i++){ var qtyWanted = GetCookie(myproducts[i]); itemqty = qtyWanted ? qtyWanted : "0"; document.dvdform[myproducts[i]+"qty"].value = itemqty; } } function addToCart(dvd){ itemqty = document.dvdform[dvd + "qty"].value; itemqty = parseInt(itemqty); SetCookie(dvd,itemqty); var feedback = "An order for " + itemqty + " dvd(s) of "; feedback += dvd.toUpperCase(); feedback += " has been added to your shopping cart."; feedback += " Please click 'Check Out' when finished." alert(feedback); } function checkOut(){ window.location.href = "return.html"; } var myAds = new Array(); myAds[1] = new Image(); myAds[2] = new Image(); myAds[3] = new Image(); myAds[4] = new Image(); myAds[1].src = "images/sh.jpg"; myAds[2].src = "images/am.jpg"; myAds[3].src = "images/sold.jpg"; myAds[4].src = "images/star.jpg"; /* Callout: The timings represent the number of milliseconds delay between the images.*/ var myTimings = new Array(); myTimings[1] = 3000; myTimings[2] = 1500; myTimings[3] = 1500; myTimings[4] = 1500; var mySites = new Array(); mySites[1] = "sh.html"; mySites[2] = "am.html"; mySites[3] = "sold.html"; mySites[4] = "star.html"; var adnumber = 0; var totalads = myAds.length - 1; var timerID = ""; function startBanner(){ adnumber = 0; showAd(); } function showAd(){ if (document.images){ /*Callout: This condition ensures that each image loads completely before the next image appears in the sequence. */ if (document.myBanner.complete){ adnumber++; (adnumber > totalads) ? adnumber=1 : adnumber=adnumber; document.myBanner.src = myAds[adnumber].src; } timerID = setTimeout("showAd()",myTimings[adnumber]); } } function goSite(){ clearTimeout(timerID); window.location.href = mySites[adnumber]; } //--> </script> </head> <body onload="showCookies(); startBanner();"> <form name="dvdform"> <div id="wrapper"> <div id="inner"> <div id="header"> <h1><img src="images/logo.png" width="519" height="63" alt="Online Movie Store" /></h1> <div id="nav"> <a href="account.html">your account</a> | <a href="cart.html">view cart</a> </div><!-- end nav --> <img src="images/movie.png" width="744" height="198" alt="Banner" /></a> </div><!-- end header --> <dl id="browse"> <dt>We Have All Your Favourite Movies</dt> <div align="CENTER"> <a href="sh.html" onclick= "goSite();return false;"><img src = "images/sh.jpg" name="myBanner" width="180" height="400" border="0" alt="Sherlock Holmes"></a></div> </dl> <div id="body"> <div class="inner"> <div class="leftbox"> <h3>Sherlock Holmes (2009)</h3> <img src="images/sh.jpg" width="80" height="100" alt="sherlock holmes" class="left" /> <p>Detective Sherlock Holmes and his stalwart partner Watson engage in a battle of wits and brawn with a nemesis whose plot is a threat to all of England.</p> <input type="TEXT" name="sherlockholmesqty" size="5" value="0"><br> <p><b>Price:</b> �3.00 per night</p> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('sherlockholmes');"> </p> <div class="clear"></div> </div><!-- end .leftbox --> <div class="rightbox"> <h3>Anchorman: The legend of Ron Burgundy (2004)</h3> <img src="images/am.jpg" width="80" height="100" alt="Anchorman" class="left" /> <p>Ron Burgundy is San Diego's top rated newsman in the male dominated broadcasting of the 1970's, but that's all about to change when a new female employee with ambition to burn arrives in his office.</p> <input type="TEXT" name="anchormanqty" size="5" value="0"><br> <p><b>Price:</b> �3.00 per night</p> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('anchorman');"></p> <div class="clear"></div> </div><!-- end .rightbox --> <div class="clear br"></div> <div class="leftbox"> <h3>We Were Soldiers (2002)</h3> <img src="images/sold.jpg" width="80" height="100" alt="we were soldiers" class="left" /> <p>The story of the first major battle of the American phase of the Vietnam War and the soldiers on both sides that fought it.</p> <p><b>Price:</b> �3.00 per night</p> <input type="TEXT" name="weweresoldiersqty" size="5" value="0"><br> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('weweresoldiers');"> </p> <div class="clear"></div> </div><!-- end .leftbox --> <div class="rightbox"> <h3>Starship Troopers (1997)</h3> <img src="images/star.jpg" width="80" height="100" alt="Starship troopers" class="left" /> <p>Humans of a fascistic, militaristic future do battle with giant alien bugs in a fight for survival.</p> <p><b>Price:</b> �3.00 per night</p> <input type="TEXT" name="starshiptroopersqty" size="5" value="0"><br> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('starshiptroopers');"></p> <div class="clear"></div> </div><!-- end .rightbox --> <div class="clear br"></div> <div class="leftbox"> <h3>Home Alone (1990)</h3> <img src="images/homealone.jpg" width="80" height="100" alt="Home Alone" class="left" /> <p>An 8-year-old boy, who is accidentally left behind while his family flies to France for Christmas, has to defend his home against idiotic burglars.</p> <p><b>Price:</b> �3.00 per night</p> <input type="TEXT" name="homealoneqty" size="5" value="0"><br> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('homealone');"> </p> <div class="clear"></div> </div><!-- end .leftbox --> <div class="rightbox"> <h3>Gamer (2009)</h3> <img src="images/gamer.jpg" width="80" height="100" alt="Gamer" class="left" /> <p>In a future mind-controlling game, death row convicts are forced to battle in a 'doom'-type environment. Convict Kable, controlled by Simon, a skilled teenage gamer, must survive 30 sessions in order to be set free. Or won't he?</p> <p><b>Price:</b> �3.00 per night</p> <input type="TEXT" name="gamerqty" size="5" value="0"><br> <p class="readmore"><input type="button" value="Add to Cart" onclick="addToCart('gamer');"> </p> <div class="clear"></div> </div><!-- end .rightbox --> <div class="clear"></div> </div><!-- end .inner --> </div><!-- end body --> <div class="clear"></div> <div id="footer"> <div id="footnav"> <a href="account.html">Your Account</a> | <a href="cart.html">View Cart</a> </div><!-- end footnav --> </div><!-- end footer --> </div><!-- end inner --> </div><!-- end wrapper --> </form> </body> </html> I think the problem is that I have 2 onload functions in the body tag *<body onload="showCookies(); startBanner();">* does anyone know how I can fix this? Also when I put the Javascript into external files they won't work! but when I included the show cookies file in the html it works does anyone know where I am going wrong? Hi there. I'm relatively new to coding in javascript, so I'm hoping that some kind souls could help me out! I'm trying to make an animated image height changer (example: changing an image's height from 50px to 500px). I'm working on a new web site using HTML5 and want to add some Flash-like animation to my page using javascript and <canvas>. The animation would only need to "play" one time once the web page has loaded. No looping is required and no user interaction (ie mouseovers, etc) is needed. Any help would be greatly appreciated. If anyone knows of similar examples online please send me a link. If you're interested in helping, please let me know if more information is needed. Thanks. Hello everyone! Recently I found a nice pop up javascript code and I had no problem editing the HTML part,but I have no knowledge in javascript. So what I would like to do is to make the pop up show every 24 hours when a visitor votes.I read somewhere that this will involve cookies but as I said I couldnt get it working. Code: <script language="JavaScript1.2"> var ns4 = document.layers; var ie4 = document.all; var ns6 = document.getElementById && !document.all; //drag drop function for NS 4//// var dragswitch = 0; var nsx; var nsy; var nstemp; function drag_dropns( name ) { if( !ns4 ) return; temp = eval( name ); temp.captureEvents( Event.MOUSEDOWN | Event.MOUSEUP ); temp.onmousedown = gons; temp.onmousemove = dragns; temp.onmouseup = stopns; } function gons( e ) { temp.captureEvents( Event.MOUSEMOVE ); nsx = e.x; nsy = e.y; } function dragns( e ) { if( dragswitch == 1 ) { temp.moveBy( e.x-nsx, e.y-nsy ); return false; } } function stopns() { temp.releaseEvents( Event.MOUSEMOVE ); } //drag drop function for ie4+ and NS6//// function drag_drop( e ) { if( ie4 && dragapproved ) { crossobj.style.left = tempx + event.clientX - offsetx; crossobj.style.top = tempy + event.clientY - offsety; return false; } else if( ns6 && dragapproved ) { crossobj.style.left = tempx + e.clientX - offsetx; crossobj.style.top = tempy + e.clientY - offsety; return false; } } function initializedrag( e ) { crossobj = ( ( ns6 ) ? document.getElementById( "showimage" ) : document.all.showimage ); var firedobj = ( ( ns6 ) ? e.target : event.srcElement ); var topelement = ( ( ns6 ) ? "HTML" : "BODY" ); while( ( firedobj.tagName != topelement ) && ( firedobj.id != "dragbar" ) ) { firedobj=ns6? firedobj.parentNode : firedobj.parentElement; } if( firedobj.id == "dragbar" ) { offsetx = ( ( ie4 ) ? event.clientX : e.clientX ); offsety = ( ( ie4 ) ? event.clientY : e.clientY ); tempx = parseInt( crossobj.style.left ); tempy = parseInt( crossobj.style.top ); dragapproved = true; document.onmousemove = drag_drop; } } document.onmousedown = initializedrag document.onmouseup = new Function( "dragapproved=false" ); ////drag drop functions end here////// function hidebox(){ if (ie4||ns6) crossobj.style.visibility="hidden" else if (ns4) document.dnwtop_100_showimage.visibility="hide" } </script> <style type="text/css"> #showimage { position:absolute; width:300px; padding:2px; } #showimage #dragbar { font-family:Trebuchet MS; font-size:10pt; text-align:left; font-weight:bold; width:280px; } #showimage #closebutton { font-family:Tahoma; font-weight:bold; height:12px; width:12px; font-size:8pt; border:2px solid; border-top-color:#EEE; border-right-color:#AAA; border-bottom-color:#AAA; border-left-color:#EEE; padding:0 3px 0 4px; color:#000; text-decoration:none; } #showimage #message { font-family:Trebuchet MS; color:#FFFFFF; font-size:10pt; font-weight:bold; padding:4px; background-color:#000000; } </style> <div id="showimage" style="left:500px;top:100px;"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td id="message" width="100%" colspan="2" align="center"> <img src="http://img822.imageshack.us/img822/79/38866885.jpg" border="0" alt=""> <br><br> <a href="http://bgtop.net/in.php/1293974162" target="_blank" onClick="hidebox(true)"><img src="http://img221.imageshack.us/img221/2269/yesw.png" border="0"></a> <a href="#" onClick="hidebox();return false"><img src="http://img195.imageshack.us/img195/6383/72081945.png" border="0"></a> </td> </tr> </table> </div> Hello all, I am new to javascript and I have run into a problem. I cant seem to be able to write to a text file called users.txt Here is my code: Code: <html> <head> <script language="javascript"> function rf() { var fs,file; fs = new ActiveXObject('Scripting.FileSystemObject'); file = fs.OpenTextFile('C:/Users/Imran/Documents/Imran IT/Web/Test/user.txt',2); file.Write('The text to write to file'); file.Close(); } </script> </head> <body onLoad="rf();"> </body> </html> What I do is I put the code in notepad, I then save it as a .html file and try run it in IE 7, google chrome and firefox, Each time users.txt is unchanged. Any help appreciated. All I want is for the client to send a variable to the server and for that variable to be saved in a .txt file. If there is another way to do that, please share Hello Everyone Smarter Than Me! Before I get to the question first a little History on what I am working with. I am a Software Engineer currently working under a contract in a highly customized environment. The IDE that I am using (Not by my choice as I am a Java developer by Trade) uses a "JavaScript Runtime Environment" to treat JavaScript as a complied language. Needless to say this is a little odd and it was created because my employer had trouble finding enough developers that know other languages (This also seems odd) but there always seemed to be a ton of JavaScript people around. Anyway now to the question. The code I am writing is product testing automation code that is going to save testing dollars eventually. Initially the testing was done by a team of testers whom would log into a website, run some tests by interacting with the website, and then get the results from the tests via the product that they are testing. My code will do all the interaction with the device and the website and then compile all the results in an Ms. Excell spreadsheet for viewing. The problem is that my employer doesn't own the website that the testing is done from and there has been some changes lately that I am trying to overcome. The problem is as follows. I have been using a Microsoft.XMLHTTP ActiveX Object to login to the website and do all the test manipulation and form submitting. The recent changes to the website have broken the automation code. The original form that I was working with contained a submit button as follows [ICODE]<input id="submitReq" type="submit" value="task device"/>[ICODE] and the id allowed the ActiveX control to find the button and submit the form. Now the page has changed as follows. There is no longer a submit button instead there is a standard button calling a javascript onclick which is then used to submit the form. The button and the javascript are below and as you can see the button has no id which makes finding and submitting the button very difficult. [CODE] <input type="button" class="button" value="Task Devices" onclick="submitRequestForm()"/> <script type="text/javascript"> <![CDATA[ function submitRequestForm() { var validations = new Object(); var fieldNames = ["devices", "profile", "priority"]; for (var key in fieldNames) { try { document.getElementById("errorMessageSpace_" + fieldNames[key]).innerHTML = ""; } catch(ex) { } } validations["devices"] = [ {type: "required", errorAction: displayTaskingParamError, errorMsg: "Devices field cannot be empty!"}, {type: "mask", regExp: /^(([!]?[\+]?([*?0-9A-Fa-f]{0,30}))|(([!]?[\+]?[0-9A-Fa-f]{0,30})?\/([0-9A-Fa-f]{0,30})?\/([*?0-9A-Fa-f]{0,30})?))(\s(([!]?[\+]?([*?0-9A-Fa-f]{0,30}))|(([!]?[\+]?[0-9A-Fa-f]{0,30})?\/([0-9A-Fa-f]{0,30})?\/([0-9A-Fa-f]{0,30})?)))*$/, errorAction: displayTaskingParamError, errorMsg: "Invalid devices list specification!"}]; validations["profile"] = [ {type: "required", errorAction: displayTaskingParamError, errorMsg: "Profile field cannot be empty!"}, {type: "mask", regExp: /^[0-9]*$/, errorAction: displayTaskingParamError, errorMsg: "Invalid profile specification!"}]; validations["priority"] = [ {type: "required", errorAction: displayTaskingParamError, errorMsg: "Priority field cannot be empty!"}, {type: "mask", regExp: /^[+-]?[0-9]*$/, errorAction: displayTaskingParamError, errorMsg: "Invalid priority specification!"}, {type: "numberBetween", low: 0, high: 1000, errorAction: displayTaskingParamError, errorMsg: "Priority value must be between 0 and 1000!"}]; var taskingRequestForm = document.getElementById('taskingForm'); taskingRequestForm.elements["devices"].value = normalizeDevicesList(taskingRequestForm.devices.value); if (new FormValidator(taskingRequestForm, validations).validate(false)) { taskingRequestForm.submit(); } } function displayTaskingParamError(field, validation) { try { document.getElementById("errorMessageSpace_" + (field.name || field.id)).innerHTML = "*" + validation["errorMsg"]; } catch(ex) { alert(validation["errorMsg"]); } } ]]> </script> [CODE] Can anyone tell me how to submit this page after the form is filled out using the Microsoft.XMLHTTP ActiveX Object? Is there a way? Thanks in advance for any help that any of you can be. Regards, I got an index.php Code: <html> <form action="bacakomik.php" method='post'> <select name="kodekomik"> <option value='../komik1/|23'>Judul Komik1</option> <option value="../komik2/|20">Judul Komik2</option> <option value="../komik3/|10">Juduk Komik3</option> <option value="../komik4/|20">Judul Komik4</option> </select> <input type="submit" /> </form> <?php echo ('<select>'); echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); echo ('</select>'); ?> </html> As you can see, each of the option brings specific value "../komik1/|23" komik1 is a directory | is a delimiter 23 is the pages in one chapter and can be considered also as how many images are there on a specific directory This is my bacakomik.php Code: <?php $dirkomik = $_POST['kodekomik']; $exploded = explode("|", $dirkomik); echo ($exploded[0]); //picture directory echo ("<br>"); echo ($exploded[1]); //total page in the comic $pagecount = (int)$exploded[1]; //Take last posted value, process it right away echo ('<FORM name="guideform"> '); echo ('<select name="guidelinks">'); $i=1; do { echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); $i= $i+1; }while($i <= $pagecount); //Printing option and select echo ("</select>"); ?> <input type="button" name="go" value="Go!" onClick="document.getElementById('im').src=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value+'.png';"> </FORM> <img src="img0.jpg" id="im"> With the current code on bacakomik.php, I only can change the img src of id "im" in the same directory only. What I want is that the Javascript could "add" the "$exploded[0]" variable so that the picture can be loaded from different directory. Anyone can do this? I believe that the fix should be somewhere on input tag inside OnClick, or do you know where? Anyway, I found this on the net http://p2p.wrox.com/php-faqs/11606-q...avascript.html Please help me to those who can... I'm almost positive this question will make you groan "neewwwbie!".... I have a simple javascript that decides which 'div' to make visible, based on another element within the html. What i want now is to create a page where someone can view all the possible divs in that javascript that might appear and edit them (including href's, ital, bold and image tags.) Much like a CMS system, but the information is within a javascript, not a database. I would assume it's possible. What's a good way to approach this? It sounds like Javascript cannot edit .txt files. Is there a way to have the user access and edit an .xml file and just pull that into the div tag, instead of text? Do many programmers remember most of the object properties and methods or do they use IDE or references to find those specific objects. I'm starting to learn Javascript and seeing all the different type of objects available can be depressing. I've successfully implemented custom images for LinkedIn and Tweet share buttons for a static HTML website - static web pages. They work fine, but the only problem is that I have to manually enter the URL and the Metadata. That's a lot of work. So, what's the best way for JavaScript and or LinkedIn/Twitter to grab the active URL, title, and summary? Any help would be appreciated. The following is what I have at the moment: Code: <a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.mydomain.com/&title=Page Title Goes Here&summary=The Summary of My Page Goes Here&source=Page Name" rel="nofollow" onclick="NewWindow(this.href,'template_window','550','400','yes','center');return false" onfocus="this.blur()"> <img src="images/linkedin_ico.png" title="Share this on LinkedIn" alt="Share this on LinkedIn" width="35" height="35" border="0" /> </a> Code: <a href="https://twitter.com/share?url=http://www.domain.com/&text=The Summary of My Page Goes Here" rel="nofollow" onclick="NewWindow(this.href,'template_window','500','400','yes','center');return false" onfocus="this.blur()"><img src='images/twitter_ico.png' border="0" title="Share this on Twitter" alt="Share this on Twitter"/></a> Hi Guys, Quick question, is there a way to stop a JavaScript from validating after a certain point of the code. I've been "googling" like crazy and cant find a solution. I had to add a Checkbox validation last second and there was existing validation and I'm not good enough to alter all of it to reflect the checkbox part so what I did was I checked to see if at least one of the checkboxes was selected, if yes, do nothing and finish the rest of the validation. If no, prompt them with an error. The problem is after it prompts them for an error, it continues to run the rest of the validation and at the end it allows the end user to print. I cannot allow the end user to print until everything is filled in. Here is my code: Code: function validateFields() { var fieldsToVerify = [ ["PrincipalInvestigator"], ["ContactEmailAddress"], ["RFAward"], ["Sponsor"], ["AwardTitle"], ["BudgetStartDate"], ["BudgetEndDate"], ["SectionII"], ["ProjectRole"], ["EmployeeName"], ["DatesofAppointment"], ["EffortonProject"], ["Date"], ["PrintName"], ["Date2"], ["PrintName2"], ]; var emptyFields = []; var notFullFields = []; for (var i=0; i<fieldsToVerify.length; i++) { var f = this.getField(fieldsToVerify[i][0]); if (f==null) { console.println(fieldsToVerify[i][0] + " not found."); continue; } if (f.valueAsString=="") { emptyFields.push(f.name); } else if (fieldsToVerify[i].length>1 && f.valueAsString.length<fieldsToVerify[i][1]) { notFullFields.push([f.name,fieldsToVerify[i][1]]); } } for (var i in nonRequiredFieldsToVerify) { var f = this.getField(nonRequiredFieldsToVerify[i]); if (f==null) { console.println(nonRequiredFieldsToVerify[i] + " not found."); continue; } if (f.valueAsString!="" && f.valueAsString.length<f.charLimit) { notFullFields.push([f.name,f.charLimit]); } } if (this.getField("CheckBox1").value=="Yes" || this.getField("CheckBox2").value=="Yes" || this.getField("CheckBox3").value=="Yes" || this.getField("CheckBox4").value=="Yes" || this.getField("CheckBox5").value=="Yes" || this.getField("CheckBox6").value=="Yes" || this.getField("CheckBox7").value=="Yes") {} else app.alert("Select a Checkbox in Section I before printing") if (emptyFields.length==0 && notFullFields.length==0) { this.print(); } else { var msg = ""; if (emptyFields.length>0) { msg += "The following fields must be filled-in:\n"; for (var i in emptyFields) msg += emptyFields[i]+"\n"; } if (notFullFields.length>0) { if (msg!="") msg+="\n\n"; msg += "The following fields are not filled-in completely:\n"; for (var i in notFullFields) msg += notFullFields[i][0] + " (required length: " + notFullFields[i][1] + ")\n"; } app.alert(msg,""); } } Thanks to Old Pedant , in this forum, I am using this basic code for a slideshow he posted: Code: var slides = [ [ "abc.jpg", 3000 ], [ "xyz.png", 5000 ], [ "foo.gif", 1500 ] ]; var curSlide = 0; function nextSlide( ) { document.getElementById("thePicture").src = slides[curSlide][0].src; setTimeout( nextSlide, slides[curSlide][1] ); curSlide = ( curSlide + 1 ) % slides.length; } function setUp( ) { for ( var s = 0; s < slides.length; ++s ) { var image = new Image(); image.src = slides[s]; slides[s] = image; } nextSlide( ); } window.onload = setUp; which works just fine. But I can't find a way for it to play one round of the slides then stop. Could someone please help me with the right bit of code to stop the show? I know the code is a bit basic (no fades etc) but I have been unable to find a similar slideshow product that gives variable time delays for each slide. I've googled endlessly but nothing could i find.... TIA Richard ========= I am using joomla, and have a tabbed menu at the top, which has different articles embedded within. I have embedded a flash video inside each article. The problem is that if i play a video and then switch to the other tab (article) without pausing the video, the video keeps on playing. And if i try to play the video in the other article, then both videos start playing. I want to stop the first video from playing as soon as I switch to the new tab. There are a lot of different files which are included in the page, so If I know where to place a particular code within the source of the final rendered webpage, I will be able to place it at the right point in a particular file. thanks the website link is: http://tinyurl.com/ycg4tcm Hi all. I have this simple javascript that initiates a flash player. Code: <script type="text/javascript"> function add_content(filedesc,filepath,whatarget) { var output = "" + filedesc + "</b><br />"; output += "<object type='application/x-shockwave-flash' data='mp3player.swf'>"; output += "<param name='movie' value='mp3player.swf'>"; output += "<param name='wmode' value='transparent'>"; output += "<param name='FlashVars' value='mp3=" + filepath + ">"; output += "</object></div>"; output += "" + whatarget + ""; document.getElementById("" + whatarget + "").innerHTML = output; } </script> and this takes care of the onclick event: Code: <a href="javascript:void;" onclick="javascript:add_content('Hello1','../m_music/omd.mp3','target1');">Omd</a><div id='target1'></div> <a href="javascript:void;" onclick="javascript:add_content('Hello2','../m_music/blondie.mp3','target2');">blondie</a> <div id='target2'></div> page and vars are going to be dynamic. My question is: if I press 'target1' it plays. When I press 'target2' second player plays in its div layer. How can I start one player while stopping another (I am guessing 'target1' must be hidden). I am going to have many mp3 files and I want each player to be in its rightful place. I've looked for functions, but I am not that experienced with JV syntax. Thank you. I am very new to Javascript - as in this is the first day I'm using it. I am using a code I got offline to fade three pictures together, but when it gets to the last image, it loops back to the first. How do I code it so that when it gets to the last image, it stops? Here is the code - sorry if its messy. Javascript: /***** Image Cross Fade Redux Version 1.0 Last revision: 02.15.2006 steve@slayeroffice.com Please leave this notice intact. Rewrite of old code found he http://slayeroffice.com/code/imageCrossFade/index.html *****/ window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so _init); var d=document, imgs = new Array(), zInterval = null, current=0, pause=false; function so_init() { if(!d.getElementById || !d.createElement)return; // DON'T FORGET TO GRAB THIS FILE AND PLACE IT ON YOUR SERVER IN THE SAME DIRECTORY AS THE JAVASCRIPT! // http://slayeroffice.com/code/imageCrossFade/xfade2.css css = d.createElement("link"); css.setAttribute("href","xfade2.css"); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); d.getElementsByTagName("head")[0].appendChild(css); imgs = d.getElementById("imageContainer").getElementsByTagName("img"); for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0; imgs[0].style.display = "block"; imgs[0].xOpacity = .99; setTimeout(so_xfade,3000); } function so_xfade() { cOpacity = imgs[current].xOpacity; nIndex = imgs[current+1]?current+1:0; nOpacity = imgs[nIndex].xOpacity; cOpacity-=.05; nOpacity+=.05; imgs[nIndex].style.display = "block"; imgs[current].xOpacity = cOpacity; imgs[nIndex].xOpacity = nOpacity; setOpacity(imgs[current]); setOpacity(imgs[nIndex]); if(cOpacity<=0) { imgs[current].style.display = "none"; current = nIndex; setTimeout(so_xfade,3000); } else { setTimeout(so_xfade,50); } function setOpacity(obj) { if(obj.xOpacity>.99) { obj.xOpacity = .99; return; } obj.style.opacity = obj.xOpacity; obj.style.MozOpacity = obj.xOpacity; obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")"; } } HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <div class="container"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="imagetoolbar" content="false" /> <link rel="stylesheet" href="style.css" type="text/css" /> <script type="text/javascript" src="slideshow.js"></script> <title>Diamonds in the Rough</title> </head> <body> <div id="container"> <img src="images/top2.jpg" usemap="#Map2"/> <map name="Map2" id="Map2"> <area shape="rect" coords="69,56,145,84" href="invite.html" rel="nofollow" target="_self" alt="The Gala" /> <area shape="rect" coords="171,53,356,87" href="diamonds.html" rel="nofollow" target="_self" alt="Diamonds in the Rough" /> <area shape="rect" coords="377,52,498,87" href="mariama.html" rel="nofollow" target="_self" alt="Speaker Mariama Elliot" /> <area shape="rect" coords="525,52,636,86" href="contact.html" rel="nofollow" target="_self" alt="Get Involved" /> </map> <div id="imageContainer"> <img src="images/index.jpg"/> <img src="images/index2.jpg"/> <img src="images/invite.jpg"/> </div> <div id="container2"> <img src="images/BOTTOM.jpg"/> </div> </body> </html> Thanks for your help! Hello and thank you for you help, we have a problem in our currently built website, in chrome+firefox the website works great but in IE 7+8+9 the javascript stops working after few seconds or after several commands a user do in the website. the url is : http://www.triver.co.il if any one know what can be the issue it will be great thank you ! Code: top.window.moveTo(0, 0); if (document.all) { top.window.resizeTo(screen.availWidth, screen.availHeight); } else if (document.layers || document.getElementById) { if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth) { top.window.outerHeight = screen.availHeight; top.window.outerWidth = screen.availWidth; } } function gcd(a, b) { return (b === 0) ? a : gcd(b, a % b); } var i = 0; var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (; i < data.length; i + 1) { var dataString = data[i].string, dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) !== -1) { return data[i].identity; } } else if (dataProp) { return data[i].identity; } } return data[i].identity; }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index === -1) { return parseFloat(dataString.substring(index + this.versionSearchString.length + 1)); } }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] }; var version; if (dataString.indexOf(dataBrowser.versionSearch) !== -1) { version = parseFloat(string.indexOf(dataBrowser.versionSearch), 1); } else { version = parseFloat(string.indexOf(dataBrowser.identity), 1); } BrowserDetect.init(); if (dataBrowser.identity === "Chrome") { if (version >= 8) { document.location.replace("main/index.htm"); } else if (version >= 3) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } else if (dataBrowser.identity === "Safari") { if (version >= 5) { document.location.replace("main/index.htm"); } else if (version >= 3) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } else if (dataBrowser.identity === "Opera") { document.location.replace("http://www.google.com/"); } else if (dataBrowser.identity === "Firefox") { document.location.replace("http://www.google.com/"); } else if (dataBrowser.identity === "Mozilla") { document.location.replace("http://www.yahoo.com/"); } else if (dataBrowser.identity === "Explorer") { if (version >= 8) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } For some reason, this script was working before I put in the if statements, but after the if statements were placed in, it stopped auto maximizing as well, and no if statements were added around this. Does anyone know what the problem is? (It's supposed to redirect by browser to one of 3 sites based on how good they are) JavaScript Code: window.addEvent('domready',function(){ //SAMPLE 8 var handles8_more = $$('#handles8_more span'); var nS8 = new noobSlide({ box: $('box8'), interval: 5000, autoPlay: true, items: $$('#box8 h3'), size: 900, handles: $$('#handles8 span'), handle_event: 'mouseenter', addButtons: { previous: $('prev8'), play: $('play8'), stop: $('stop8'), playback: $('playback8'), next: $('next8') }, onWalk: function(currentItem,currentHandle){ //style for handles $$(this.handles,handles8_more).removeClass('active'); $$(currentHandle,handles8_more[this.currentIndex]).addClass('active'); //text for "previous" and "next" default buttons $('prev8').set('html','<< '+this.items[this.previousIndex].innerHTML); $('next8').set('html',this.items[this.nextIndex].innerHTML+' >>'); } }); //walk to item 0 witouth fx nS8.walk(0,false,true); }); html Code: <div class="slider sample8"> <p class="buttons" id="handles8"> <span>Item 1</span><span>Item 2</span><span>Item 3</span><span>Item 4</span><span>Item 5</span> </p> <div class="mask1"> <div id="box8"> <div onMouseOver="nS8.Stop();" onMouseOut="nS8.Play();"> </div> </div> </div> <p class="buttons"> <span id="prev8"><< Previous</span> | <span id="next8">Next >></span> </p> <p class="buttons"> <span id="playback8">< Playback</span> <span id="stop8">Stop</span> <span id="play8">Play ></span> </p> </div> All I need to do is when they hover ocer the div statement stop the program from looping. and then when they stop hovering over it let it start looping again. Is there a way to stop a form submit after hitting submit? Refresh wouldn't realy be an option. Is abort() what I'm looking for?
I am very new to javascript and cannot find any info anywhere regarding the following problem: On my website I have around 100 pages containing an action form. Occasionally it is necessary to cancel the action throughout the 100 pages which is very time-consuming. Then the action has to be reinstated once again for all the 100+ pages. I thought the solution would be to use javascript to change the action from a .js file which would mean only one page, the .js file, would require alteration: The action that appears on all 100+ pages several times that I am trying to change or stop happening by overwriting the "form action": <form action="http://www.changenamecart.com/" method="post"> <input type="hidden" name="userid" value="1234567"> <input type="hidden" name="return" value="http://www.thehomepage.co.uk/index.htm"> <input type="image" src="http://www.changenamecart.com/images/pic.gif"> </form> My efforts to date a The change .js file: function change() { var myChange = form action; if(myChange == form action){ document.write("form xction"); } } The html file in the header: <script src="change.js" type="text/javascript"></script> I am afraid that my knowledge of programming is very small and I would welcome any help to solve this problem. I have created a small file where I check if the passwords entered in the code match or not, if they do not match, the button that links to the next webpage should not work(allow them to go to the next wepage). ive tried various websites to help me try and solve this but I just dodont understand what they are doing. I'm very new to programming btw here is some example code: Code: !doctypeHTML <html> <script> //lets just pretend that ive already done all the .getelement by id stuff to get the code things //suppose the person did not write anything in the form, an error will get pushed(alerted basically) if(!form['password'].value) error.push('Missing Password'); <form> <label>Password<br><input type="password" name="password"></label> <label>Confirm Password<br><input type="password" name="confirm"</label> </form> </html> now how would I make the submit button not submit if there are errors? please be as simple as possible, I am new to this! |