Search code examples
jquerytoggleclass

jQuery image toggle


Having issues using jQuery to toggle from one image to another. Not getting any console errors, so I'm not sure what the issue is - any suggestions would be appreciated.

HTML:

    <main>
        <div id="bathroom" class="switch"> </div>
    </main>

CSS:

#bathroom {
    position: absolute;
    top: 20%;
    left: 42%;
    height: 100%;

}

.switch {
    background-image: url('women.png');

}

.switchOn {
    background-image: url('men.png');
}

jQuery:

$('#bathroom').click(function(){

$('#bathroom').toggleClass('switchOn switch');

}); 

You can see it here in action, though not much is happening. I had the women.png showing for a little bit, and then it just disappeared.

https://jsfiddle.net/c1g47o5u/


Solution

  • Your code is good, except of two tiny things:

    • jquery is not included in your jsfiddle
    • the div with the click event has no width

    so put a

    width: 200px;
    

    into the #bathroom to make the div clickable.

    Here is a fixed version of the jsfiddle: https://jsfiddle.net/2optdrbp/1/