treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Annoying jQuery Issue

  • I am creating a custom jQuery slideshow with dynamically generated pagination. There is a #slides div containing all the images. When the page is loaded, the following is ran:

    $("#slides img").each(function(index) {
    $(this).attr("id", index); // Image class = index (0, 1, 2 etc)
    slideCount++;
    // Generate Pagination and CSS
    if (index != 0) {
    $("#pagination").append("<img src='img/dot-empty.png' class='pagination' id='p" + index + "' alt='Navigate to " + index + "' />");
    $(this).css("display", "none");
    } else {
    $("#pagination").append("<img src='img/dot-full.png' class='pagination' id='p" + index + "' alt='Navigate to " + index + "' />");
    }
    });


    So, a generated pagination item looks like this:

    <img src="img/dot-empty.png" class="pagination" id="p1" alt="Navigate to 1" />


    When you click an arrow to navigate through slides, jQuery throws an exception when this code is ran:

    ("#p" + currentSlide).attr("src", "img/dot-empty.png");


    The error generated says "Object #p1 has no method 'attr'." (#p1 is just an example, it could be #p5 or #p300). I can't for the life of me understand why. The incredibly frustrating aspect is that when I type the command into the console, it runs perfectly. I just can't run it through the script.
  • It is just a typo, or is that really missing a "$"?
    $("#p" + currentSlide).attr("src", "img/dot-empty.png");
    If that was just a typo, then add a check to make sure the element exists, like this:
    var p = $("#p" + currentSlide);
    if (p.length){
    p.attr("src", "img/dot-empty.png");
    }