How to add click loop function in JQuery?


I created a list containing 4 items:

<body class="body">
<div class="carousel-container">
  <ol class="carousel">
    <li id="fire" class="carousel-item"><a href="#">Fire</a></li>
    <li id="ice" class="carousel-item"><a href="#">Ice</a></li>
    <li id="wind" class="carousel-item"><a href="#">Wind</a></li>
    <li id="darkness" class="carousel-item"><a href="#">Darkness</a></li>

I want each item click changes background images, but the way I did it in JQuery is bad:

  $('#fire').on("click", function(){
  $('#ice').on("click", function(){
  $('#wind').on("click", function(){
  $('#darkness').on("click", function(){


body {
  height: 100vh;
  overflow: hidden;

.carousel-container {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
  height: 97%;

.carousel-item {
  display: inline;
  border: 1px solid green;
  padding: 10px;

.carousel-item a {
  text-decoration: none;
  color: black;

.carousel-item a:hover {
  color: white;

.fire, .ice, .wind, .darkness {
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 0;

.fire {
  background-image: url('');

.ice {
  background-image: url('');

.wind {
  background-image: url('');

.darkness {
  background-image: url('');

#fire:hover {background: rgb(226, 88, 34);}
#ice:hover {background: rgb(109,155,195);}
#wind:hover {background: #8cc5f2;}
#darkness:hover {background: rgb(85,26,139);}

It’s like it’s creating layers, so when I click the button again the background image doesn’t change.
May you please give me a better function to do this?

Thank you

Working Code: Codepen

You can use removeClass to remove the other classes that you don’t want to be there. The class names can be space-separated, to remove multiple classes a the same time.

Hi @Sora, you can use the removeClass() method then to remove previously added classes before adding the new one:

var classNames = ['fire', 'ice', 'wind', 'darkness']

$('#fire').on('click', function () {

$('#ice').on('click', function () {

$('#wind').on('click', function () {

$('#darkness').on('click', function () {

Of course, writing that out for every carousel item is tedious and hard to maintain; given that every class name is the same as the item’s ID, you might directly map those IDs to the class names like so:

var $items = $('.carousel-item')
var $body = $('.body')

var classes = $ () {

$items.on('click', function () {

This way you don’t have to hard-code any ID / class relations in your JS at all… here’s the updated pen.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.