Fortytwo Fortytwo - 19 days ago 6
jQuery Question

JQuery addClass not working

I have a code that show and hide a div and when the div is opened or closed the opacity and color changes. Instead of using JQuery .css() to add CSS directly to the element, I want to use addClass, but I cannot figured out why code below is not working.

I am getting the message 'ReferenceError: $ is not defined' when I run the build. I am not sure what that means either. Help please.

JQuery

$(document).ready(function() {
$(".upload-panel-container").click(function(e) {
$(".upload-menu-container").toggleClass("open").slideToggle(100, "linear");
if ($(".upload-menu-container").hasClass("open")) {
$(".upload-panel-container").addClass("setOpacityto1");
} else {
$(".upload-panel-container").addClass("setOpacityto85");
}
});

});


CSS

.setopacityto1 {
opacity: 1;
color: red;
}

.setopacityto85{
opacity: .85;
color: blue;
}

Answer

"$ is not defined" usually means that jQuery has not loaded to your page properly. So the $ (jQuery syntax) is not recognised

UPDATE: I FIXED IT. Your class names are case sensitive, make sure you use the same name in CSS and JS. You need to not only ADD classes where you want changes, but also REMOVE them; otherwise each time you click, the class will be added again, and you will end up with both classes added to the element. (inspect the element to see what i mean.)

$(document).ready(function() {
    $(".upload-panel-container").click(function() {
        $(".upload-menu-container").toggleClass("open").slideToggle(100, "linear");
        if ($(".upload-menu-container").hasClass("open")) {
            $(".upload-panel-container").addClass("setopacityto1");
            $(".upload-panel-container").removeClass("setopacityto85");
        } else {
            $(".upload-panel-container").addClass("setopacityto85");
            $(".upload-panel-container").removeClass("setopacityto1");
        }
    });

});