jsfiddle - http://jsfiddle.net/zE4Y7/
Demo - http://www.ttmt.org.uk/closure/
I have two arrays, one containing phrases, one containing fonts.
I'm using a loop to create 3 div's containing <p> tags.
In each <p> I'm placing a random phrase from the first array.
Each <p> is then styled with the font in the second array.
First <p> should be styled with the first font in the array, second <p> second font etc.
My problem is all the phrases are styled with the last font in the array. I think I know why it's happening and I need a closure to stop it. I'm trying to do the closure like this but it's not working.
Can anyone help me with closures.
<script>
createFlags = function(){
var text = ['Hello Sailor','Acid Test','Bear Garden','Botch A Job','Dark Horse','Face','IKEA','Jig'];
var fonts = ['CALIBRI','CORBEL','SourceSans'];
for(var i = 0; i<fonts.length; i++){
var ranNum = Math.floor(Math.random()*text.length);
(function(n){
$('#wrap').append('<div class="font"><p>'+text[ranNum]+'</p></div>').css({'font-family':fonts[n], 'font-size':'3em'});
})(i);
}
}
createFlags();
</script>
-
1It has nothing to do with closures, the font is no aplied and thus inherited from the parent div.kirelagin– kirelagin2013年06月10日 20:37:55 +00:00Commented Jun 10, 2013 at 20:37
1 Answer 1
The problem is that .append returns not the new element, but the one that you've appened to, so you style the parent div each time. Do this:
$('<div class="font"><p>'+text[ranNum]+'</p></div>').appendTo('#wrap')
instead of
$('#wrap').append('<div class="font"><p>'+text[ranNum]+'</p></div>')