Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

"Uncaught ReferenceError: $ is not defined" Can someone glance at Line 2 of this js code please! Thanks,

<section class="demo">
  <button class="next">Next</button>
  <button class="prev">Previous</button>
  <div class="container">
    <div style="display: inline-block;">
      <img src="http://placeimg.com/400/200/people"/>
    </div>
    <div>
     <img src="http://placeimg.com/400/200/any"/>
    </div>
    <div>
      <img src="http://placeimg.com/400/200/nature"/>
    </div>
    <div>
      <img src="http://placeimg.com/400/200/architecture"/>
    </div>
    <div>
      <img src="http://placeimg.com/400/200/animals"/>
    </div>
    <div>
      <img src="http://placeimg.com/400/200/people"/>
    </div>
    <div>
      <img src="http://placeimg.com/400/200/tech"/>
    </div>
  </div>
</section>

In console it says line 2: $ is not defined of the js code below. Can someone please help me out a little, thanks.

var currentIndex = 0,
  items = $('.container div'),
  itemAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display','inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemAmt - 1;
  }
  cycleItems();
});

2 Answers

Have you made sure to include jQuery before your JavaScript? Also, are you using WordPress by chance?

You were both correct thanks for your help, @rydavim answer has disappeared and cant select best answer for Ryan Duchene which is weird. Thanks again.

$(document).ready(function () {  //code here

});