Home > Enterprise >  How can I swap html classes by jquery or any solution
How can I swap html classes by jquery or any solution

Time:12-24

There is image below, look for buttons (Rent, Buy, Sell). When I click on any of the listed buttons(Rent, Buy, Sell) the selected button should have a white background and the rest of the buttons should be without a background. Shortly the selected button should change styles and be recognized as selected.

$("#search-item2").on("click", function() {
  $(this).addClass("search__item--selected");
  $("#search-item1").removeClass("search__item--selected");
});
.search__item--selected {
  background-color: hsla(0, 0%, 100%, 0.7);
  backdrop-filter: blur(10px);
  color: var(--text-color);
  text-transform: uppercase;
  border-radius: 15px 15px 0 0;
  padding: 7px 29px;
}

.search__item {
  font-size: 14px;
  text-transform: uppercase;
  color: var(--text-color2);
  cursor: pointer;
  padding: 7px 29px;
}

:root {
  --text-color: blue;
  --text-color2: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div  id="search-item1">
    <p >Rent</p>
  </div>
  <div  id="search-item2">
    <p >Buy</p>
  </div>
  <div  id="search-item3">
    <p >Sell</p>
  </div>
</div>

Image

CodePudding user response:

Add '.search__item' to each of the rent/buy/sell divs.

On click event, remove '.search__item--selected' and add this class for the clicked element

$(".search__item").on("click", function() {
  $(".search__item").removeClass("search__item--selected");
  $(this).addClass("search__item--selected");
});
body {
  background: #b6b5b5;
}

.search__item--selected {
  background-color: hsla(0, 0%, 100%, 0.7);
  backdrop-filter: blur(10px);
  color: var(--text-color);
  text-transform: uppercase;
  border-radius: 15px 15px 0 0;
  padding: 7px 29px;
}

.search__item {
  font-size: 14px;
  text-transform: uppercase;
  color: var(--text-color2);
  cursor: pointer;
  padding: 7px 29px;
}

:root {
  --text-color: blue;
  --text-color2: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div  id="search-item1">
    <p >Rent</p>
  </div>
  <div  id="search-item2">
    <p >Buy</p>
  </div>
  <div  id="search-item3">
    <p >Sell</p>
  </div>
</div>

  • Related