HannahHunt HannahHunt - 5 months ago 10
jQuery Question

jQuery uncaught reference error $foo is not defined

I'm trying to expand and collapse single divs on click using jQuery on the Laravel Spark framework. My code is mostly coming from the answer to this question.

When the selectShow text is clicked, the alert works fine, but the console shows this error "Uncaught ReferenceError: $selectShow is not defined". Even if I use the exact code from the link I provided, I get the error. A quick search mentioned that jQuery needs to be the first thing to load, but I've already placed this function in the document ready function block. Also, the alert works fine (as do other jQuery functions I'm using), which is why I don't think that this is an issue with loading jQuery improperly.

There's probably a simple answer to this, but I'm at a loss. Thanks.

Code:

<div class="mediaContainer">
<div class="selectShow"><span>Show Media</span></div>
<div class="media">
<img src="myurl.com" alt="Image unavailable">
</div>
</div>


.mediaContainer {
width:100%;
}
.mediaContainer div {
width:100%;
}
.mediaContainer .selectShow {
font-size: 12px;
color: #0084B4;
padding: 5px;
cursor: pointer;
}
.mediaContainer .media {
display: none;
}


$(".selectShow").click(function () {
alert('Click!');
$selectShow = $(this);
$media = $selectShow.next();
$(".media").not($media).slideUp().prev().text("Show Media");
$media.slideToggle(500, function () {
$selectShow.text(function () {
return $media.is(":visible") ? "Hide Media" : "Show Media";
});
});

});

Answer

You're code can work as-is, but you may be running into problems with global name collision and your $selectShow ends up being overwritten.

So solve this, declare you local variables with var. Then they will not pollute the global space, and you can avoid naming collision with other uses of the variable.

$(".selectShow").click(function () {
    alert('Click!');
    var $selectShow = $(this);
    var $media = $selectShow.next();
    $(".media").not($media).slideUp().prev().text("Show Media");
    $media.slideToggle(500, function () {
        $selectShow.text(function () {
            return $media.is(":visible") ? "Hide Media" : "Show Media";
        });
    });
});