Help with Closures

Hi all

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>

Hi,

The problem is this line:

$('#wrap').append('<div class="font"><p>'+text[ranNum]+'</p></div>').css({'font-family':fonts[n], 'font-size':'3em'});

What you’re doing is assigning the css styles to div#wrap, and each time the loop runs it’s overwriting the values.

You need to create your new element, assign the styles, and then append it to div#wrap:

for(var i = 0; i<fonts.length; i++){
    var ranNum = Math.floor(Math.random()*text.length);
    var el = $('<div class="font"><p>'+text[ranNum]+'</p></div>').css({'font-family':fonts[i], 'font-size':'3em'});
    $('#wrap').append(el);
}

You don’t actually need the extra function wrapped around your jQuery.

Hi the problem is that you are applying the font declaration to $("#wrap").

Try this instead:

for(var i = 0; i<fonts.length; i++){
  var ranNum = Math.floor(Math.random()*text.length), 
       frag = $('<div class="font"><p>'+text[ranNum]+'</p></div>');
  frag.css({'font-family':fonts[i], 'font-size':'3em'});
  $('#wrap').append(frag);
}

Edit: Oops, beaten to it. Nice one fretburner :slight_smile:

Thanks Pullo, fretburner