Wednesday, February 27, 2013

The Curious Case of Missing 'px' in Javascript for Chrome/Safari/Firefox


When one uses the transitional DOCTYPE in Chrome/Safari/Firefox, your Javascript assignment of value to marginTop or top will not be successful if you left out the 'px'.

For example, if you want to move a dummy DIV to a height of 100 pixel from the top, you might do this:


document.getElementById('dummy').style.top = 100;



It will work if you are not using the transitional DOCTYPE. If you are using the transitional DOCTYPE, you need to assign it with a 'px' at the end:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> .
.
.
document.getElementById('dummy').style.top = 100 + 'px';



in order to make it work for Chrome/Safari/Firefox.

As for IE, it will work whether it is in transitional (quirks) mode or not.

Read More »

Friday, February 1, 2013

Javascript to Change Div & Body Style in IFrame

Before showing the codes, here are the conditions that these codes WON'T work:
  • Run with Chrome in localhost environment
  • Cross domain for the main HTML and dummy.html in your iframe. These codes have to comply with the same domain policy or hackers will be very happy if it is not


The Main HTML:


<iframe id="myFrame" scrolling="no" style="overflow: hidden; height: 580px; width: 325px;"
src="dummy.html"></iframe>

<script>

function changeColor() {

    document.getElementById('myFrame').contentWindow.document.getElementById('divInDummy').
style.backgroundColor = '#123456'; // myFrame is the name of your iframe,
divInDummy is the DIV name in the iframe


    document.getElementById('myFrame').contentWindow.document.body.style.backgroundColor = "#234567";
// change the body color of iframe

}

changeColor();

</script>




The dummy.html:



<html>

<body bgcolor="#ccaaee">

Hello World! My name is dummy.html
<div id=divInDummy style="background:#55aadd;width:120px;height:120px">
<table><tr><td><br> <br><br>I am inside a DIV<br><br>
</td></tr></table>
</div>

</body>

</html>



If you think the dummy.html is not able to load before you call the script, you can put it in an interval loop to make sure the function is called successfully eventually. Here's the code: setInterval('changeColor()', 1000);

Read More »