JavaScript - Update Element Style In Ie
Hi All,
I'm using the following code to (try to) update the style of an element in javascript. As you'll no doubt gather from the code, I'm trying to edit the opacity of the element. This code executes fine in FF, Opera and Chrome. However, Internet explorer keeps responding with 'style is null or not an object'. Basically, I don't think it's returning the correct element from the DOM, or, for that matter, any element. To add some more specific guidance, on the homepage I call launch_randomise() in the onload method, which, after 5 seconds, calls randomise_bottom_images() which calls itself and the bottom image regeneration function every 5 seconds, ensuring the images are regenerated every five seconds. Regenerating the bottom images is a three-step process: 1, fade out, 2 switch innerHTML, 3, fade back in. My functions for altering the opacity or innerHTML quite obviously rely on being able to talk about a DOM object, I know no other way of achieving this. I tried straight out getElementById but this doesn't seem to work in IE8, fine in FF, Op, GC. So, after much googling I replaced getElementById(string) with my own getElement(string). However, this still doesn't work. Any thoughts? Any help would be much appreciated!! Getting elements/setting style functions Code: function getElement(id, type) { var inputs = document.getElementsByTagName(type); var descField = null; for(var i=0;i<inputs.length;i++) { if(inputs.item(i).getAttribute('id') == id ) { descField = inputs.item(i); break; } } return descField; } // setStyleById: given an element id, style property and // value, apply the style. // args: // i - element id // p - property // v - value // function setStyleById(i, p, v) { //var n = document.getElementById(i); var n = getElement(i, 'div'); n.style[p] = v; } Full Code: Code: function getElement(id, type) { var inputs = document.getElementsByTagName(type); var descField = null; for(var i=0;i<inputs.length;i++) { if(inputs.item(i).getAttribute('id') == id ) { descField = inputs.item(i); break; } } return descField; } // setStyleById: given an element id, style property and // value, apply the style. // args: // i - element id // p - property // v - value // function setStyleById(i, p, v) { //var n = document.getElementById(i); var n = getElement(i, 'div'); n.style[p] = v; } function replace_html(el, html) { if( el ) { oldEl = (typeof el === "string" ? document.getElementById(el) : el); newEl = document.createElement(oldEl.nodeName); // Preserve any properties we care about (id and class in this example) newEl.id = oldEl.id; newEl.className = oldEl.className; //alert(newEl.id); //set the new HTML and insert back into the DOM newEl.innerHTML = html; // alert(newEl.innerHTML); if(oldEl.parentNode) oldEl.parentNode.replaceChild(newEl, oldEl); else oldEl.innerHTML = html; //return a reference to the new element in case we need it return newEl; } }; function populate_array() { // this function's sole job is to populate the array of items to be used. var da = new Array(8); da[0] = new Array(3); da[0][0] = "portfolio/garage_conversion_before.jpg"; da[0][1] = "portfolio/garage_into_kitchen.jpg"; da[0][2] = "pfimage1"; da[1] = new Array(3); da[1][0] = "portfolio/refurb_old.jpg"; da[1][1] = "portfolio/refurb_new.jpg"; da[1][2] = "pfimage2"; da[2] = new Array(3); da[2][0] = "portfolio/fireplace_old.jpg"; da[2][1] = "portfolio/fireplace_new.jpg"; da[2][2] = "pfimage3"; da[3] = new Array(3); da[3][0] = "portfolio/bathroom1_old.jpg"; da[3][1] = "portfolio/bathroom1_new.jpg"; da[3][2] = "pfimage4"; da[4] = new Array(3); da[4][0] = "portfolio/kitchen1_old.jpg"; da[4][1] = "portfolio/kitchen1_new.jpg"; da[4][2] = "pfimage5"; da[5] = new Array(3); da[5][0] = "portfolio/bathroom2_old.jpg"; da[5][1] = "portfolio/bathroom2_new.jpg"; da[5][2] = "pfimage6"; da[6] = new Array(3); da[6][0] = "portfolio/bathroom3_old.jpg"; da[6][1] = "portfolio/bathroom3_new.jpg"; da[6][2] = "pfimage7"; da[7] = new Array(3); da[7][0] = "portfolio/ext1_old.jpg"; da[7][1] = "portfolio/ext1_new.jpg"; da[7][2] = "pfimage8"; return da; } function switchimage(folioItemNum, ImageState) { var isOpera, isIE = false; if(typeof(window.opera) != 'undefined'){isOpera = true;} if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true;} // folioItemNum tells us which folio item to access, // ImageState tells us which image to set. // we will use ajax/dom to re-write the document. var OldImageState = 1 - ImageState; // 2d array of items. var darray = populate_array(); // take one item and fade out opacity(darray[folioItemNum][2], 100, 0, 500); // re-arrange. // with time delay. window.setTimeout(function (a,b,c,d,e){ var y = "<a href=\"" + c + "\" rel=\"lightbox[" + d + "]\" class=\"hiddenimg\"><img src=\"" + c + "\" class=\"folioimghidden\"/></a><a href=\"" + b + "\" rel=\"lightbox[" + d + "]\"><img src=\"" + b + "\" class=\"folioimg\"/></a>"; replace_html(e, y); opacity(e, 0, 100, 500); },500,document.getElementById(darray[folioItemNum][2]),darray[folioItemNum][ImageState],darray[folioItemNum][OldImageState],folioItemNum,darray[folioItemNum][2]); // done. } function regenbottomimgs() { var isOpera, isIE = false; if(typeof(window.opera) != 'undefined'){isOpera = true;} if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true;} var array = Array(3); array[0] = -1; array[1] = -1; array[2] = -1; array[0] = get_unique_random_int(6, array, 3); array[1] = get_unique_random_int(6, array, 3); array[2] = get_unique_random_int(6, array, 3); var darray = populate_array(); var imgstr = "<img src=\"" + darray[array[0]][1] + "\" class=\"scaleddown1\" /><img src=\"" + darray[array[1]][1] + "\" class=\"scaleddown2\" /><img src=\"" + darray[array[2]][1] + "\" class=\"scaleddown2\" />"; opacity("bottomimgs", 100, 0, 500); window.setTimeout(function (a,b){ var x = replace_html(b, a); opacity(b, 0, 100, 500); },500,imgstr,"bottomimgs"); } function get_random_int(Max) { var randomnumber = Math.round( Math.random() * Max ); return randomnumber; } function get_unique_random_int(Max, List, List_Length) { var stop = 1 var esc = 0 var x = 0; var i = 0; while ( stop == 1 ) { esc = 0; x = get_random_int(Max); for ( i = 0; i < List_Length; i++ ) { if ( x == List[i] ) { esc = 1; break; } } if ( esc == 0 ) { stop = 0; } } return x; } function randomise_bottom_images() { regenbottomimgs(); setTimeout("randomise_bottom_images()",5000); } function launch_randomise() { setTimeout("randomise_bottom_images()", 5000); } function switchallnew() { switchimage(0,1); switchimage(1,1); switchimage(2,1); switchimage(3,1); switchimage(4,1); switchimage(5,1); switchimage(6,1); switchimage(7,1); } function opacity(id, opacStart, opacEnd, millisec) { //speed for each frame var speed = Math.round(millisec / 100); var timer = 0; //determine the direction for the blending, if start and end are the same nothing happens if( opacStart > opacEnd ) { for(i = opacStart; i >= opacEnd; i--) { setTimeout(function (opacity, id) { setStyleById(id, "opacity", (opacity / 100)); setStyleById(id, "MozOpacity", (opacity / 100)); setStyleById(id, "KhtmlOpacity", (opacity / 100)); setStyleById(id, "filter", "alpha(opacity=" + opacity + ")"); },(timer * speed), i, id); timer++; } } else if(opacStart < opacEnd) { for(i = opacStart; i <= opacEnd; i++) { setTimeout(function (opacity, id) { setStyleById(id, "opacity", (opacity / 100)); setStyleById(id, "MozOpacity", (opacity / 100)); setStyleById(id, "KhtmlOpacity", (opacity / 100)); setStyleById(id, "filter", "alpha(opacity=" + opacity + ")"); },(timer * speed), i, id); timer++; } } } Thanks, A. Similar Tutorialsif I have an html page that uses the <style> or a <link> to call a style sheet these properties aren't available to JavaScript is there a good way to access them? eg Code: <html> <head> <title>expandable text area</title> <style type="text/css"> #expandable{ height: 100px; } </style> </head> <body> <form> <textarea id="expandable" cols="30" rows="10"></textarea> </form> </body> <script type="text/javascript"> document.getElementById('expandable').addEventListener('click',function(){ if(!this.style.height){ this.style.height = this.scrollHeight+'px'; } alert(this.style.height); }, true); </script> </html> In this example I have the height set but I cannot access it since it is not declared in the style attribute of the html element Here is my code... Code: <html> <head> <script type="text/javascript"> function nameofmonth(month) { var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December") return monthname[month] } function monthdays(month,year) { var daysofmonth=new Array(31,28,31,31,30,31,31,31,30,31,30,31) if(year%4==0) daysofmonth[1]=29 return daysofmonth[month] } function close(){ document.getElementById("container").style.display='none' } function table() { var now=new Date() var hour=now.getHours() var minute=now.getMinutes() var second=now.getSeconds() var date=now.getDate() var month=now.getMonth() var year=now.getFullYear() now.setFullYear(year,month,1) var firstday=now.getDay() var monthname=nameofmonth(month) var daysofmonth=monthdays(month,year) if(firstday>0) var k=-(firstday-1) else k=1 var table="<table border=5 cellspacing=3cellpadding=8>" table +="<tr><th colspan=7>"+monthname + date+"th</th> <td style='cursor:pointer' onclick='close()'>[close]</td></tr>" table +="<tr><th>sun</th><th>mon</th><th>tue</><th>wed</th><th>thu</th><th>fri</><th>sat</th></tr>" for(var i=0;i<5;i++) { table+="<tr>" for(var j=0;j<7;j++) { if(k<=daysofmonth && k>0) { if(k==date) table+='<td id="clock" bgcolor="aqua">'+k+'</td>' else table+='<td style="cursor:pointer">'+k+'</td>' k=parseInt(k) } else table+="<td></td>" k++ } table+="</tr>" document.getElementById("calender").innerHTML=table } } </script> </head> <body> <input type="text" onclick="table()"/> <table id="container"><tr><td id="calender"></td></tr></table> </body> </html> HERE is a close cell in table.when it is clicked,the close() function will called and the calender will disappear.but it is not happening.please help me ,what is wrong.Thanks in advance... Hi all, I'm working on a script which is actually a very simple tab system. Code: <script> window.addEvent('domready', function() { var tabs = $$('div[id^="tab"]'); tabs.fade('hide'); $$('#buttons li a').each(function(element,index){ element.addEvent('click',function(){ tabs.fade(0); tabs[index].fade(1); }); }); }); </script> <ul id="buttons"> <li><a href="#">button 1</a></li> <li><a href="#">button 2</a></li> <li><a href="#">button 3</a></li> <li><a href="#">button 4</a></li> </ul> <div id="tab1">content for button 1</div> <div id="tab2">content for button 2</div> <div id="tab3">content for button 3</div> <div id="tab4">content for button 4</div> I'm trying to change the style of the selected button. I mean that the button which is selected each time, should be highlighted (bold text). How can I add this function in the existing code? Can you help me please? I'm using the 1.2.0 version of mootools for this. I have an idea for a little script.....I'm just stuck on one little part: When a user changes the value in a input or textarea box, I want it to change the value of a certain hidden input tag too. Here's what I have so far: function getNewValue(inputhidden, textinput) { var data = document.getElementById(inputhidden); var text = document.getElementById(textinput); data.value = text.value; } <input type= "text" name= "name" id= "name" onChange="getNewValue('detail', 'name')"> <input type= "hidden" name= "detail" id="detail" value= ""> However, this is not working and I'm not sure why The following code works find in firefox and chrome. In IE, it only works the first time I click on a link. Any ideas? Thanks in advance, // I have some div's where help is, which I make non-viewable <div id='help_guides'> <div id='issue1'>Help with issue 1</div> <div id='issue2'>Help with issue 2</div> </div> <a href="#" id="issue_1_link">Help with issue #1</a> <a href="#" id="issue_2_link">Help with issue #2</a> <div id='help'></div> // I grab the help guide div into a variable var issue_1_help = $('issue_1').remove(); var issue_2_help = $('issue_2').remove(); // When the help link is clicked, the help DIV displays the help guide Event.observe( $('issue_1_link'), 'click', function() { $('help').update( issue_1_help ); }); Event.observe( $('issue_2_link'), 'click', function() { $('help').update( issue_2_help ); }); The bit of code in bold in the code below is giving me this error in IE: Error: Code: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; Tablet PC 2.0; InfoPath.2; OfficeLiveConnector.1.4; .NET CLR 3.0.30729; OfficeLivePatch.1.3; MSN OptimizedIE8;ENGB) Timestamp: Tue, 16 Mar 2010 15:07:11 UTC Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917) Line: 0 Char: 0 Code: 0 URI: http://www.mateinastate.co.uk/users/mateinastate Code: Code: if(document.getElementById('msn1').innerHTML=="") { document.getElementById('msn1').style.display='none'; } if(document.getElementById('yahoo1').innerHTML=="") { document.getElementById('yahoo1').style.display='none'; } if(document.getElementById('skype1').innerHTML=="") { document.getElementById('skype1').style.display='none'; } if(document.getElementById('facebook1').innerHTML.toLowerCase().substr(0,18)=='<a href="http://">') { document.getElementById('facebook1').style.display='none'; } else if(document.getElementById('facebook1').innerHTML.toLowerCase().substr(0,11)=='<a href="">') { document.getElementById('facebook1').style.display='none'; } else { document.getElementById('fbook-add').innerHTML='Facebook Profile'; } What it's saying isn't actually true (I don't think)... this is how the section is laid out: Code: <div id="submenu1" class="anylinkcss"> <ul> <li class="contact-pm"><a href="/index.php?do=pm&act=new&to=$RateViewProfileUserName$&returnurl=$ReturnURL$">PM me</a></li> <li class="contact-email"><a href="/index.php?do=email&id=$RateViewProfileUserId$">E-mail me</a></li> <li class="contact-msn" id="msn1">$RateViewProfileUser-profile_msn$</li> <li class="contact-yahoo" id="yahoo1">$RateViewProfileUser-profile_yahoo$</li> <li class="contact-skype" id="skype1">$RateViewProfileUser-profile_skype$</li> <li class="contact-facebook" id="facebook1"><a href="$RateViewProfileUser-profile_facebook$"><span id="fbook-add"></span></a></li> </ul> </div> <script type="text/javascript" src="/html_1/js/contact-information.js"></script> Does anyone know why this might error in just IE? Hi, I'm relativly new to JS and brand new to the forum so you might need to dumb down your replys for my slightly lacking knowledge. That being said I do have a very solid grasp of html, css and am getting there with JS and its various frameworks. I'm integrating wordpress into an existing site for a friend and currently have the main blog page appear in a DIV. This is the best way to integrate in this case due to many reasons mostly of way the site is constructed. Code: <div class="scroll-pane" id="scrollbox"> WORDPRESS BLOG </div> My issue is that links within that DIV, in the blog, when clicked redirect the page. The simple answer to this would be to have them just open in a new page, which I can easily do with the below code. Code: function Init() { // Grab the appropriate div theDiv = document.getElementById('scrollbox'); // Grab all of the links inside the div links = theDiv.getElementsByTagName('a'); // Loop through those links and attach the target attribute for (var i=0, len=links.length; i < len; i++) { // the _blank will make the link open in new window links[i].setAttribute('target', '_blank'); } } window.onload = Init; But what I'd rather it do is have any link clicked inside the DIV to reload in that same DIV, similar to an iframe, but obviously without using an iframe, due to it's compatibility issues. Is this possible by editing the above code? If not what do I need? Thanks in advance for any help! Hi, (new to javascript) Code: digAudio = document.createElement("audio"); digAudio.setAttribute('src',hypeDocument.documentName()+'_Resources/'+'digging.m4a'); digAudio.id = "diggingAudio"; newAudio = document.getElementById("diggingAudio"); //returns null the audio element is added (I can play the audio) but I can't get it by its id ? thank you I have the following code Code: <div class="thdnrml"> <td><a href="somelink">fonfof</a></td> </div> what i want to do is this: Code: <div class="thdnrml"> <td><a href="somelink">fonfof</a><a href="anotherlink">another_link</a></td> </div> how can i go about achieving this? Hello. I am setting up a simple registration page for a community arts project, but I am new to JS and having some issues. Right now I have a list of check boxes like this: Code: <input type="checkbox" id="HA0001" onclick="updateTotal()" /> Wendy Day <input type="checkbox" id="HA0002" onclick="updateTotal()" /> Al Benne <input type="checkbox" id="HA0003" onclick="updateTotal()" /> Julie Steppe What I would like to do is GET the input boxes ID value - which will be different for every checkbox. That value will correspond with a variable of the same name in my javascript code, that will be added or subtracted from the users total cost. So when a box is clicked, I need my variable (called "currentId") to update to the ID value, such as "HA0001" - etc. I was thinking something along the lines of this, but I know it is incorrect: Code: var currentId = document.getElementById.id; All the other add/subtract stuff I will figure out, but I am having a problem getting the ID value from a checkbox when it is clicked. Can anyone help me figure this out? THANKS! -AJ Hi I have DropdwonList with elements, 1,2,3 and 4.. and I have another DropdownList with options Normal, Standard, Emegency, and Expendited. Can you help me with a code, so that when I select "1" option on the first dropdown, the "Emegency" option on the second dropdown is set/selected. Thanks in advance I know for sure that lastRowTD_s[i] does not have "textarea" element ! The whole page is html valid. Code: else if (lastRowTD_s[i].getElementsByTagName('textarea')) { alert(lastRowTD_s[i].id); //checked, it is the row that does not have "textarea" element. alert(lastRowTD_s[i].getElementsByTagName('textarea')); // gives me [Object HTML collection] !? alert(lastRowTD_s[i].getElementsByTagName('textarea')[0]); //gives me "undefined", heh where has it gone since previous line ? } I'm trying to add an input element to all forms using appendChild. The script first searches for input elements with the name of "myinput". If it finds an input element with that name, it assigns the value "myvalue". If it can't find an input element with that name, it tries to create a new one for all forms. Code: if (document.getElementsByName('myinput')) { var testcode = document.getElementsByName('myinput'); for (var i=0; i < testcode.length; i++){ testcode[i].value = "myvalue";} } else { var z = document.createElement("input"); z.type = "hidden"; z.name = "myinput"; z.value = "myvalue"; z.id = "mycode"; var d = document.getElementsByTagName('form'); for (var i=0; i < d.length; i++){ d.appendChild(z);} } What's wrong with my code? Thanks! HI I want to write a search for my site .I make a new panel in the left of my menue and it has a text input and an image which when that user click on it javascript opens a new window which is a php page.The part I don't know how to do is when the user click on the image it should get the content of the text input and pass it to the url.For the hyperlink of the image I use "<a href="javascriptpen_window('includes/func/search.php?id=" But I don't know what should I write after that to get the content of the text input and put it in the next of the id. How can I do so? Thanks Ok, Simpler question. I'm trying to get the text in an xml element. Instead of getting just the text in the first child element I'm getting the text of all the children elements. How can I get it from just the first? Code: var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); function xmlload(filexml) { xmlDoc.async="false"; xmlDoc.load(filexml); xmlObj=xmlDoc.documentElement; } xmlload('urlhere'); document.getElementById("nmbr").value=myVar; myVar = xmlObj.childNodes(0).childNodes(19).firstChild.text; document.getElementById("comment_t").innerText= myVar; Hello I am fairly new to Javascript and found this code online but can't seem to get it to work right. here is the code I am using it is suppose to apply a style attribute the the id "toplink" but I can't seem to get it to work right. Code: $(document).ready(function(){ menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px"))) $(window).scroll(function () { var offset = menuYloc+$(document).scrollTop()+"px"; $("#toplink").animate({top:offset},{duration:500,queue:false}); }); }); Thanks in advance Alright, this is going to sound strange, but bear with me here... Code: <input type="text" name="_F0827U" size="015" maxlength="015"> <input type="submit" class="cmdkey" name="_K040827" value="..."> Say I have multiple isntances that look similar to the above. However, I have no possible way of identifying them uniquely (because I don't know the name prior to generation). Is it posable, using JS, to snag the previous element and strip it of it's tags then rewrite a new element isntead of the two originals, say using an onClick() event on either of the elements? Im trying to duplicate an image multiple times here is what I have Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> var totalNumber = 1000; function insert(num) { var cont = document.getElementById("cont"); var img = document.createElement("img"); var percent = num/totalNumber; var result = cont.offsetWidth * percent; var dup = result/100*2; img.src = "guy.jpg"; cont.appendChild(img); } </script> <style type="text/css"> #cont {height:100px; width:500px;} </style> </head> <body> <div id="cont"></div> </body> <script type="text/javascript"> insert(3000); </script> </html> So Im trying to get img to repeat the variable "dup" so you would see <img src="guy.jpg"> 30 times. I am using a jQuery slider for a website but the W3C comes up with invalid because: document type does not allow element "div" here .before('<div id="buttons">') Code: <script type="text/javascript"> $(document).ready(function() { $('#slider') .before('<div id="buttons"></div>') .cycle({ fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc... pager: '#buttons' }); }); </script> Any help with this would be appreciated thanks. Hi all Not sure how to tackle this. I haven't done any DOM manipulation and this is a tag within a tag. Another thing is submit is Ajax and therefore can be hit many times --- so I guess I need to also check if element already exists. The result comes back from PHP and I think wipes out anything in the result area. I want to create this: Code: <span id="loading"><img src="loading.gif" /></span> Code: <div id="results">which should populate here</div> <script type="text/javascript"> function loading(){ ? </script> <input type="button" name="submit" id="submit" onclick="loading();"/> How do I begin this? Help appreciated. LT oh this is my Ajax just in case what i'm trying to do should be done from here. Code: <script type="text/javascript"> $(document).ready(function() { $('#submit').click(function(){ //Get the values var amount = $('#amount').val(); var from = $('#from').val(); var to = $('#to').val(); var params = "amount=" + amount + "&from=" + from + "&to=" + to; $.ajax({ type: "POST", url: "change.php", data: params, success: function(data){ $('#results').html(data).fadeIn("slow"); } }); }); }); </script> |