mdnash mdnash - 7 months ago 15
Javascript Question

Need helping getting this string of Javascript to work

Here is what I am working with:

<script>

$(document).ready(function() {

$("#cf7_controls").on('click', 'span', function() {

$("#cf7 img").removeClass("opaque");

var newImage = $(this).index();

$("#cf7 img").eq(newImage).addClass("opaque");

$("#cf7_controls span").removeClass("selected");

$(this).addClass("selected");

});

});

</script> <div class="row">
<div class="span 6">
<div id="cf7" class="shadow">
<img class='opaque' src="/img/Cirques.jpg" />
<img src="/img/ClownFish.jpg" />
<img src="/img/Stones.jpg" />
<img src="/img/Summit.jpg" />
</div>
<p id="cf7_controls">
<span class="selected">Image 1</span>
<span>Image 2</span>
<span>Image 3</span>
<span>Image 4</span>
</p>
</div>
<div class="span 6">
<div id="cf7" class="shadow">
<img class='opaque' src="img/Cirques.jpg" />
<img src="img/ClownFish.jpg" />
<img src="img/Stones.jpg" />
<img src="img/Summit.jpg" />
</div>
<p id="cf7_controls">
<span class="selected">Image 1</span>
<span>Image 2</span>
<span>Image 3</span>
<span>Image 4</span>
</p>
</div>


I pulled this code from http://css3.bradshawenterprises.com/cfimg/#cfimg7

Unfortunately, it doesn't work right. A live demo of my WIP can be viewed on http://marc-with-a-c.com

The error in google chrome is:
Uncaught ReferenceError: $ is not defined marc-with-a-c.com/:97

Thanks for helping!

Answer

You does not have jQuery library included in the page

Add the line to include jQuery before the script element:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    $(document).ready(function() {

        $("#cf7_controls").on('click', 'span', function() {
            $("#cf7 img").removeClass("opaque");

            var newImage = $(this).index();

            $("#cf7 img").eq(newImage).addClass("opaque");
            $("#cf7_controls span").removeClass("selected");
            $(this).addClass("selected");
        });
    });
</script>
Comments