Skip to content

Instantly share code, notes, and snippets.

@davertron
Created May 18, 2010 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davertron/405125 to your computer and use it in GitHub Desktop.
Save davertron/405125 to your computer and use it in GitHub Desktop.
<html>
<head>
<script type="text/javascript">
// The purpose of this function is to draw a div inside another div
// at half dimensions (sort of like looking at a mirror in another
// mirror...
function turtles_all_the_way_down(previous_div, level, max_level){
if(level == max_level){
return;
}
var new_div = document.createElement('div');
var previous_div_style = previous_div.getAttribute('style');
var height_regex = /height:\s*([0-9]+)/;
var width_regex = /width:\s*([0-9]+)/;
var color_regex = /background-color:\s*([^;]*);/;
var height_match = height_regex.exec(previous_div_style);
var width_match = width_regex.exec(previous_div_style);
var color_match = color_regex.exec(previous_div_style);
var previous_height = height_match[1];
var previous_width = width_match[1];
var previous_color = color_match[1];
if(previous_color.replace(' ', '') == 'red'){
var new_color = 'blue';
} else {
var new_color = 'red';
}
new_div.setAttribute('style', 'height: ' + previous_height/2 +
'px; width: ' + previous_width/2 + 'px; ' +
'background-color: ' + new_color + ';');
previous_div.appendChild(new_div);
turtles_all_the_way_down(new_div, level+1, max_level);
}
</script>
</head>
<body>
<div id="starter_div" style="height: 500px; width: 500px; margin: auto;
background-color: red;">
</div>
<a
href="javascript:turtles_all_the_way_down(document.getElementById('starter_div'),
0, 5);">Draw 6 Nested Divs</a>
</body>
</html>
@davertron
Copy link
Author

This was a test that a friend had for an interview, so I tried my hand at it. Could probably be fixed up a bit here and there and made more robust, but it does what it needs to do :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment