JavaScript - Javascript: Animated Image Height Changer
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. Similar TutorialsI may be too close to this to see the answer but i have an image viewer with one big image and lots of little ones. What i need is that when you click on one of the smaller ones it grabs it's image src and sets the larger photo to that src. The small images are dynamic but the larger image will have a static id.
Hey, I'm working on a script that uses a function (called on click) to change the content of a div (called description) within the page. It contains an unordered list and list items. The first one has the class "show" and the ID "1", the second with just the ID "2", and so forth. (see code below). I am using jQuery to control the onclick function. the jQuery gets the current object with the "show" class. If there is no show class, it takes the first. It then puts a variable string together that represents the UL LI that is needed to be shown. Code: var descurrent = ($('div#description ul li.show')? $('div#description ul li.show') : $('div#description ul li:first')); var desclass = '#description li#'+x; Note: x is a variable transfered from the function change(x); where x is the ID that is to be shown HTML CODE: Code: <div id="description"> <ul> <li class="show" id="1">blahblah </li> <li id="2"> etc </li> </ul> The jQuery i'm trying to get to work is: Code: //Hide the current image descurrent.animate({opacity: 0.0}, 1000) .removeClass('show'); //Show new image $(desclass).addClass('show') .animate({opacity: 1.0}, 1000); Note: the class "show" has a higer z-index Thanks in advance, Hope this can be resolved soon, been giving me headaches! Cheers, John Hi there, I just recently took over a site that has some java code on it I'm unfamiliar with. If you go to smalltowngossipmusic.com, you'll see what this code does. Go to the pages "Sounds" or "Travel", and once your mouse leaves the main image at the top of the page, you should see those pages shrink. This is some code that was implemented on the site (which is wordpress) in the header.php template. Here is the code: Code: <script type="text/javascript"> /* <![CDATA[ */ var $ = jQuery.noConflict(); $(document).ready(function () { headerImage(); }); var speed = 500; var origMT = 0, origHeight = '120px'; function expandHeader(obj) { $('.headerImage').animate({height: '436px'},speed); $('.headerImage img').animate({'margin-top': '-2px'},speed); } function shrinkHeader(obj) { $('.headerImage').stop().animate({'height': origHeight},speed); $('.headerImage img').stop().animate({'margin-top': origMT},speed); } function headerImage() { origMT = $('.headerImage img').css('margin-top'); origHeight = $('.headerImage').css('height'); $('.headerImage img').css('margin-top','0'); $('.headerImage').css('height','436px'); setTimeout(shrinkHeader,speed*2); $('.headerImage').hover(expandHeader, shrinkHeader); } /* ]]> */ </script> If you look at the page source for each page, you'll see that there is nothing out of whack (at least, not that I can find). However, for some reason, this shrinking script only works on the two pages I mentioned - on every other page, it either doesn't work at all, or it only works about half-way. I have made sure the page.php and header.php templates both have accurate picture information in them, and can not find anything wrong anywhere. Is there any advice anyone here can give me on how to fix this? I've been doing html and css for awhile, but am relatively new to javascript and php, so am a bit out of my element on this. I'm willing to post any more code, snippets, whatever needed, just let me know what you need if you think you can help. Thanks, Brandon Hi 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? 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] } } } } Hi I have this code to change the color of elements in a div. But I cant code the active,followed and visited links .how to do that? Code: <html> <head> </head> <body> <script> function fun() { var bg=document.getElementById("t1").value; var txt=document.getElementById("t2").value; var al=document.getElementById("t3").value; var vl=document.getElementById("t4").value; var hv=document.getElementById("t5").value; document.getElementById("dv").style.backgroundColor=bg; document.getElementById("dv").style.alinkcolor=txt; document.getElementById("dv").style.vlinkcolor=al; document.getElementById("dv").style.color=vl; document.getElementById("dv").style.color=hv; } </script> <h1>Enter Colors: </h1> Background: <input type="text" id="t1" name="txt1"><br/><br/> Text: <input type="text" id="t2" name="txt2"><br/><br/> Link: <input type="text" id="t3" name="link"><br/><br/> Active Link: <input type="text" id="t4" name="alink"><br/><br/> Followed Link: <input type="text" id="t5" name="vlink"><br/><br/> <input type="button" value="test" onclick="fun();"><br/><br/> <div id="dv"> hello This is a Test<br/> You Have Selected These Colors<br/> <a href="#">This is a Test Link</a><br/></div> </body> </html> Plz help me. Thnx in advance Hi, on my site, I have added Style 1 and Style 2 in my menu at the top right http://www.thisisworthing.com/default.php# when I click on Theme 2, it doesn't work?! please help! I have this working on my other site: http://www.mypubspace.com what am i doing wrong?! Hi, I am no very little when it comes to Javascript but I have seen a few sites using pre populated text boxes for login forms. So Username and password appears in the boxes to save space. The code below works fine onload of the site in all browsers, everything also works fine in firefox but ie the following doesn't seem to work. When a user clicks to enter their password in i.e. it doesn't change the form to password characters so input plain text. Also when you click out of either box it doesn't seem to re-populate the boxes with my Username or Password text. Any help would greatly be appreciated. Code: <script> function HideLabel(txtField){ if(txtField.name=='myusername'){ if(txtField.value==txtField.defaultValue) txtField.value = ''; else txtField.select(); } else if(txtField.name=='mypassword'){ if(txtField.value==txtField.defaultValue){ txtField.value = ''; txtField.type = 'password'; } else{ txtField.type = 'password'; txtField.select(); } } } function ShowLabel(txtField){ if(txtField.name=='myusername'){ if(txtField.value.trim()=='') txtField.value = txtField.defaultValue; }else if(txtField.name=='mypassword'){ if(txtField.value.trim()==''){ txtField.value = txtField.defaultValue; txtField.type = 'text'; } } } </script> <input type="text" name="myusername" id="myusername" onfocus="HideLabel(this)" onblur="ShowLabel(this)" style="border:0;" value="Username" /> <input type="test" name="mypassword" id="mypassword" value="Password" onfocus="HideLabel(this)" onblur="ShowLabel(this)" style="border:0;" /> Hi. I have a JavaScript that resizes an image held within an Iframe. It works perfectly, BUT only works if there is an alert box in the code. /*Image resizing scripts - Dependant on page size!*/ /////////////////////////////////// function Im_Resize() { var imheight = 550; /*Change the IFrame CSS*/ iframeheight = imheight + 15; /* +15px for the x-axis scroll bar*/ var IFrame = document.getElementById('MainFrame'); IFrame.style.height = iframeheight + 'px'; alert('after iframe size - before im change'); /*Change the Image CSS*/ var innerdoc = IFrame.contentDocument || IFrame.contentWindow.document; Image1 = innerdoc.getElementById('MainImg1'); Image1.style.height = imheight + 'px'; } If I take the alert box out the code just doesn't work?? I thought that it was that during the loading of the page an element hadn't been loaded yet, but a delay doesn't work either. If I press 'ok' on the alert box too quick it doesn't work either. In terms of HTML this script is run whenever the page is loaded and is also fired when a click event is detected on one of the divs on the page. Any help would be great Ed Can someone tell me why this short script won't work? <script type="text/JavaScript"> <!-- function timedRefresh(timeoutPeriod) { var number = rand(7); if (number == 1) { var bgcss = "theme1.css"; } else if (number == 2) { var bgcss = "theme2.css"; } else if (number == 3) { var bgcss = "theme3.css"; } else if (number == 4) { var bgcss = "theme4.css"; } else if (number == 5) { var bgcss = "theme5.css"; } else if (number == 6) { var bgcss = "theme6.css"; } else if (number == 7) { var bgcss = "theme7.css"; } document.write('<link href="bgcss "'+ 'type=text/css rel=stylesheet>'); } // --> </script> </head> <body onload="JavaScript:timedRefresh(10000);"> hey guys i downloaded the 'Content Slider v2.4', and this has a feature which will save a cookie used to remember and recall the last content viewed by the user when they return to the page. (click here for more information on the script.) the only thing is that this is made for pages with URLs such as: Quote: www.mysite.com/gallery_album_1/content.php but my URLS are set out like: Quote: www.mysite.com/content.php?gallery_album_1 is there a way to make to so the cookie remembers the page via the "php?gallery_album_1" part instead of the "content.php" part. i need it to be like this simply because i have multiple galleries coming from the oe page, eg: Quote: www.mysite.com/content.php?gallery_album_1 www.mysite.com/content.php?gallery_album_2 www.mysite.com/content.php?gallery_album_3 the main code of the js is as follows: Code: //** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** May 2nd, 08'- Script rewritten and updated to 2.0. //** June 12th, 08'- Script updated to v 2.3, which adds the following features: //1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later. //2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former). //3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example. //** July 11th, 08'- Script updated to v 2.4: //1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider") //2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads. var featuredcontentslider={ //3 variables below you can customize if desired: ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="../images/loading.gif" /> Fetching slider Contents. Please wait...</div>', bustajaxcache: true, //bust caching of external ajax page after 1st request? enablepersist: true, //persist to last content viewed when returning to page? settingcaches: {}, //object to cache "setting" object of each script instance jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually. this.turnpage(this.settingcaches[fcsid], pagenumber) }, ajaxconnect:function(setting){ var page_request = false if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false var pageurl=setting.contentsource[1] page_request.onreadystatechange=function(){ featuredcontentslider.ajaxpopulate(page_request, setting) } document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcache, true) page_request.send(null) }, ajaxpopulate:function(page_request, setting){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ document.getElementById(setting.id).innerHTML=page_request.responseText this.buildpaginate(setting) } }, buildcontentdivs:function(setting){ var alldivs=document.getElementById(setting.id).getElementsByTagName("div") for (var i=0; i<alldivs.length; i++){ if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv" setting.contentdivs.push(alldivs[i]) alldivs[i].style.display="none" //collapse all content DIVs to begin with } } }, buildpaginate:function(setting){ this.buildcontentdivs(setting) var sliderdiv=document.getElementById(setting.id) var pdiv=document.getElementById("paginate-"+setting.id) var phtml="" var toc=setting.toc var nextprev=setting.nextprev if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){ for (var i=1; i<=setting.contentdivs.length; i++){ phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> ' } phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '') pdiv.innerHTML=phtml } var pdivlinks=pdiv.getElementsByTagName("a") var toclinkscount=0 //var to keep track of actual # of toc links for (var i=0; i<pdivlinks.length; i++){ if (this.css(pdivlinks[i], "toc", "check")){ if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents) pdivlinks[i].style.display="none" //hide this toc link continue } pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link pdivlinks[i][setting.revealtype]=function(){ featuredcontentslider.turnpage(setting, this.getAttribute("rel")) return false } setting.toclinks.push(pdivlinks[i]) } else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next" pdivlinks[i].onclick=function(){ featuredcontentslider.turnpage(setting, this.className) return false } } } this.turnpage(setting, setting.currentpage, true) if (setting.autorotate[0]){ //if auto rotate enabled pdiv[setting.revealtype]=function(){ featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation this.autorotate(setting) } }, urlparamselect:function(fcsid){ var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, turnpage:function(setting, thepage, autocall){ var currentpage=setting.currentpage //current page # before change var totalpages=setting.contentdivs.length var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage) turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly return setting.currentpage=turntopage setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex this.cleartimer(setting, window["fcsfade"+setting.id]) setting.cacheprevpage=setting.prevpage if (setting.enablefade[0]==true){ setting.curopacity=0 this.fadeup(setting) } if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete) setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.prevpage, setting.currentpage) } setting.contentdivs[turntopage-1].style.visibility="visible" setting.contentdivs[turntopage-1].style.display="block" if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[setting.prevpage-1], "selected", "remove") if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[turntopage-1], "selected", "add") setting.prevpage=turntopage if (this.enablepersist) this.setCookie("fcspersist"+setting.id, turntopage) }, setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=setting.contentdivs[setting.currentpage-1] if (targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value setting.curopacity=value }, fadeup:function(setting){ if (setting.curopacity<1){ this.setopacity(setting, setting.curopacity+setting.enablefade[1]) window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50) } else{ //when fade is complete if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run) setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.cacheprevpage, setting.currentpage) } }, cleartimer:function(setting, timervar){ if (typeof timervar!="undefined"){ clearTimeout(timervar) clearInterval(timervar) if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div setting.contentdivs[setting.cacheprevpage-1].style.display="none" } } }, css:function(el, targetclass, action){ var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig") if (action=="check") return needle.test(el.className) else if (action=="remove") el.className=el.className.replace(needle, "") else if (action=="add") el.className+=" "+targetclass }, autorotate:function(setting){ window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1]) }, 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){ document.cookie = name+"="+value }, init:function(setting){ var persistedpage=this.getCookie("fcspersist"+setting.id) || 1 var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index this.settingcaches[setting.id]=setting //cache "setting" object setting.contentdivs=[] setting.toclinks=[] setting.topzindex=0 setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1) setting.prevpage=setting.currentpage setting.revealtype="on"+(setting.revealtype || "click") setting.curopacity=0 setting.onChange=setting.onChange || function(){} if (setting.contentsource[0]=="inline") this.buildpaginate(setting) if (setting.contentsource[0]=="ajax") this.ajaxconnect(setting) } } as far as i can see, the parts of the code which are about the cookies are labeled "enablepersist" thanks guys Hi! I installed the Animated Information Bar found on http://www.javascriptkit.com/script/.../infobar.shtml Now there is a option to display the bar once per session but this isn't working... Code: infobar.setfrequency('session') //Uncomment this line to set information bar to only display once per browser session! Anyone has installed this bar and knows why this isn't working? I use IE8 greetings Jardin Holland Hello This is brilliant and good to work with, there is one issue i have if someone can help please. I have used example 4 bacuase it visually does exactly what i need, however there is one little problem i cant solve. I copied the div and now have 2 collapsible divs next to each other, which nearly do exactly what i need. I have lined up the 2 divs next to each other they both open, but the one on the left pushes the right one out to the right and i don't know how to do that. here is the code thanks the animatedcollapse.js is too long to put but can be found here http://www.dynamicdrive.com/dynamici...edcollapse.htm Code: <script type="text/javascript"> animatedcollapse.addDiv('jason', 'fade=1,height=80px') animatedcollapse.addDiv('kelly', 'fade=1,height=100px') animatedcollapse.addDiv('michael', 'fade=1,height=120px') animatedcollapse.addDiv('cat', 'fade=0,speed=400,group=pets') animatedcollapse.addDiv('dog', 'fade=0,speed=400,group=pets') animatedcollapse.addDiv('rabbit', 'fade=0,speed=400,group=pets,hide=1') animatedcollapse.ontoggle = function ($, divobj, state) { //fires each time a DIV is expanded/contracted //$: Access to jQuery //divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID //state: "block" or "none", depending on state } animatedcollapse.init() </script> <div id="mobile_navigation"> <div id="sectionnav"> <a href="#" rel="toggle[dog]" data-openimage="section_active.gif" data-closedimage="section.gif"><img src="collapse.jpg" border="0" /></a> <div id="dog"> The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines, is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship and its ability to hunt vermin. It has been associated with humans for at least 9,500 years. A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple commands. </div> </div> <div id="searchnav"> <a href="#" rel="toggle[cat]" data-openimage="search_active.gif" data-closedimage="search.gif"><img src="collapse.jpg" border="0" /></a> <div id="cat"> The cat (Felis catus), also known as the domestic cat or house cat to distinguish it from other felines, is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship and its ability to hunt vermin. It has been associated with humans for at least 9,500 years. A skilled predator, the cat is known to hunt over 1,000 species for food. It can be trained to obey simple commands. </div> </div> </div> I have an animated gif of a door opening on my site. The animated gif is triggered onclick. (It's triggered only when the user clicks on a certain part of the door, hence the image map). This is the current code: <img src="img/door_admin_static.gif" width="229" height=401" alt="admindoor" usemap="#admin" name="animate"> <map name="admin"> <area shape ="rect" coords ="65,165,236,501" onClick="document.images.animate.src='img/door_admin.gif'; return true" href ="admin.html" rel="nofollow" target="_self" alt="admin" /> </map> What is supposed to happen is that after the user clicks, the animation of the door opening runs, and then the user is taken to the page linked to that door (in this case, admin.html). As it is now, the user is taken immediately to the admin.html page, so they never get to see the animation run. I need some kind of code that makes it so that the user is taken to the admin.html only after the animation is complete. Any help would be greatly appreciated!! Hey guys, I'd like to think this is fairly simple but unfortunately my knowldege of jquery is limited to using prebuilt scripts and changing a few variables to get what i need. I created a drop down menu with a slide down/up animation for submenus, which worked out just as I wanted. I ran into troubles though when trying to add a nested menu to the drop down, but with a slide animation going from left to right. I'm sure my explanation isn't very clear, so please take a look http://www.palousehillscomputing.com...rop/index.html The nested submenu I am speaking of should only open when hovering occurs on the 'Item 01' link, but as you can see it also opens when hovering over the buyers link. Secondly, my attempt to slide from left to right on this ul is not working. It seems to be sliding down even though this was not defined in the code. I've tried playing around with it for a while now and can't seem to figure this out so I'd appreciate if someone pointed me in the right direction. Thanks Hello, i wanna make animated news bar like the one in the top of site alibaba.com, so how can i do that, anybody have any kind of tutorial for any thing like this please ? thanks Hi, I searched the web for a button that can be animated, as well as dynamic. but I couldn't find one, so I decided to try my hand at creating one. My method is similar to a post made by Bram2: http://codingforums.com/showthread.php?t=153326, however, I have found my code to be unreliable and it doesn't apply only to the area where the table is, instead of spreading across the screen. The reason for trying to create a button this way is because I'm lazy, I don't want to create a new button in a graphics editor, spending hours trying to make it uniform with the rest of the buttons on the page, every time I want a new button. Doing it this way will also enable to have buttons with mulitple lines of text. I am fairly new to javascript, so I am wondering if anyone can give me a hand making it more reliable or pointing me to a script that has already been created. I put the button Here instead of filling the post with code. Please look at it before telling me it can be done with the <button> tag, because I tried before posting here. thanks, grayatrox Edit:I have managed to get the code to do what I wanted it to do, and more efficently too. Old code is commented out in the orginal webpage. This is a working example on how to impliment the buttons. javascript: Code: /* Notes: - Each button MUST have a unique name. - You may need to create a secondary function that the button can activate like I did with the go(url) function below. - Email me (grayatrox) at 238atrox@gmail.com for bugs, or to suggest improvements. - Yes I know tables within tables is bad, if you read through my code carefully you will see where I am talking about. */ function loadButton() { //preload the buttons. image1 = new Image(); image1.src = "images/button_up_L.png"; //button up left image2 = new Image(); image2.src = "images/button_up_C.png"; //button up centre image3 = new Image(); image3.src = "images/button_up_R.png"; //button up right image4 = new Image(); image4.src = "images/button_down_L.png"; //button down left image5 = new Image(); image5.src = "images/button_down_C.png"; //button down centre image6 = new Image(); image6.src = "images/button_down_R.png"; //button down right } function createButton(buttonName, buttonText, buttonAction, id) { // create the code for a button output= "<table border='0' cellpadding='0' cellspacing='0' id="+buttonName+">"; output=output+"<tr name="+buttonName+" onclick=\""+buttonAction+"\" onmouseover=\"changeButton('down', '"+buttonName+"')\" onmouseout=\"changeButton('up', '"+buttonName+"')\">"; output=output+"<td align='right'><img id='"+buttonName+"_leftImage' src='images/button_up_L.png'/></td>"; output=output+"<td id='"+buttonName+"_middleImage' align='middle' background='images/button_up_C.png'/>"+buttonText+"</td>"; output=output+"<td align='left'><img id='"+buttonName+"_rightImage' src='images/button_up_R.png'/></td>"; output=output+"</tr>"; output=output+"</table>"; return output; } function writeButton(buttonName, buttonText, buttonAction) { // write button immediatly below where function has been called document.write(createButton(buttonName, buttonText, buttonAction)); } function writeButtonInId(buttonName, buttonText, buttonAction, id) { // write the button in an id document.getElementById(id).innerHTML=createButton(buttonName, buttonText, buttonAction); } function changeButton(action, name) { // button animation if (action== "up") { document.getElementById(name+'_leftImage').src="images/button_up_L.png"; document.getElementById(name+'_middleImage').style.backgroundImage ="url(images/button_up_C.png)"; document.getElementById(name+'_rightImage').src="images/button_up_R.png"; } else if (action== "down") { document.getElementById(name+'_leftImage').src="images/button_down_L.png"; document.getElementById(name+'_middleImage').style.backgroundImage ="url(images/button_down_C.png)"; document.getElementById(name+'_rightImage').src="images/button_down_R.png"; } } function go(url) { // written becuase there were too many ' and ". You can do this for any javascript function (I hope) document.location=url; } Does anyone have an explanation for why animated .gifs might not animate in FF, Chrome, etc.? Only IE does it right for me. I suspect it might have something to do with tables squeezing the graphic (if the .gif is inside a table with a 100% width cell... but even giving the cell with the .gif a width doesn't seem to help.) Is it true? I realise tables are not best used for this purpose, but did this also happen in the good old tables days? I am trying to do what I thought was a very simple animated menu. I have a heading at the top of a website - which is just a png. I have a menu that is simply a div with a few options on it arranged horizontally. There's no submenus, it's just a very simple horizontal list. All I am trying to do is to hide the menu and then when you mouseover the heading, it will drop down. When you mouseout, it will move back up. It would be great if it faded in as it moved down too. Am sure it's probably very simple, but I've looked all over Google and I can't find a simple solution that doesn't do X, Y and Z that I don't want or need in this project. I just need a very simple script that I stand half a hope of understanding! |