Robert Deniro Robert Deniro - 4 months ago 10
jQuery Question

Jquery toggleClass not toggling class

I have this div that displays 4 images and I am trying to get this jQuery function so that when I click on the image, it toggles a class which makes the image increase in size. Pretty simple, but I can't figure out why the code isn't toggling the

.exampleimgopen
class. I have linked the jquery script and all that to my html

<div id="examples">
<p>Examples:</p>
<img src="img/1.png" class="exampleimg">
<img src="img/2.png" class="exampleimg">
<img src="img/3.png" class="exampleimg">
<img src="img/1.png" class="exampleimg">
</div>


The CSS for this code is:

#examples {
background-color:white;
color:black;
text-align:center;
padding:5px 5px 5px 5px;
}

.exampleimg {
padding:10px 0px 10px 0px;
width:300px;
margin:0 20px 0 20px;
}

.exampleimg:hover {
opacity:0.8;
cursor:pointer;
}

.exampleimgopen {
width:600px;
}


And the jQuery for this is:

jQuery(document).ready(function($) {
$('#examples').click(function() {
$('.exampleimg').toggleClass('.exampleimgopen');
});
});

Answer

Remove the dot in toggleClass('.exampleimgopen')

jQuery(document).ready(function($) {
    $('#examples').click(function() {
        $('.exampleimg').toggleClass('exampleimgopen');
    });
});
#examples {
    background-color:white;
    color:black;
    text-align:center;
    padding:5px 5px 5px 5px;
}

.exampleimg {
    padding:10px 0px 10px 0px;
    width:300px;
    margin:0 20px 0 20px;
}

.exampleimg:hover {
    opacity:0.8;
    cursor:pointer;
}

.exampleimgopen {
    width:600px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="examples">
    <p>Examples:</p>
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
</div>

If you want this on each image, do like this

jQuery(document).ready(function($) {
    $('.exampleimg').click(function() {
        $(this).toggleClass('exampleimgopen');
    });
});
#examples {
    background-color:white;
    color:black;
    text-align:center;
    padding:5px 5px 5px 5px;
}

.exampleimg {
    padding:10px 0px 10px 0px;
    width:300px;
    margin:0 20px 0 20px;
}

.exampleimg:hover {
    opacity:0.8;
    cursor:pointer;
}

.exampleimgopen {
    width:600px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="examples">
    <p>Examples:</p>
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
    <img src="http://placehold.it/300" class="exampleimg">
</div>

Comments