-1

I am trying to use this fiddle http://jsfiddle.net/C6LPY/2/

$(function () {
    var parent = $("#shuffle");
    var divs = parent.children();
    while (divs.length) {
        parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
});

On my site here:

https://github.com/craiglockwood/confheroes/blob/master/index.html but am getting a 'can't find variable' error.

The idea is to shuffle the divs in random order each time the page loads. The fiddle works but somehow, not with my code.

Any help greatly appreciated.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
Craiginwlaes
  • 29
  • 2
  • 5
  • Then the issue probably lies with code not contained in the fiddle. Try to narrow it down further. – Dan Wilson Nov 23 '16 at 18:28
  • 1
    You've used the snippet from your post in the `head` of your page, but you don't include jQuery until the bottom of the `body`. You're trying to use jQuery before the page knows what it is. You can either move your snippet to be after the jQuery include, or move the jQuery include to the `head` before your snippet. – Tyler Roper Nov 23 '16 at 18:30
  • Your code is missing jQuery library. – spooky Nov 23 '16 at 18:32
  • ah - rooky error! Many thanks – Craiginwlaes Nov 23 '16 at 18:35

1 Answers1

0

Order is important

Move the inline javascript with your IIFE after the script referencing jQuery - either in the head element or towards the end of the body element (read this post for more information about benefits of placing them towards the end of the body element). Otherwise the jQuery code won't be available to the inline script. For more information about including external scripts, refer to this guide.

<script type='text/javascript'>
  //jQuery should not be loaded yet, so typeof $ should return undefined
  console.log('typeof $ before including jQuery: ',typeof $);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<!-- at this point, jQuery should be defined, and $ should be usable as a shortcut for it.-->
<script type='text/javascript'>
  //ensure typeof $ is a function, otherwise it is likely the case that jQuery did not load
  console.log('typeof $ after including jQuery: ',typeof $);
  $(function() {
    var parent = $("#shuffle");
    var divs = parent.children();
    while (divs.length) {
      parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
  });
</script>
<div id="shuffle">ShuffleDiv
  <div>child div 1</div>
  <div>child div 2</div>
  <div>child div 3</div>
</div>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58