What is the best way to set up a condition that only runs if an element does not contain a certain class, such as "active"?

Click here for the picture I have a list of items: a, b, c, d, e, f. Whenever I click on item b, it becomes active and the other elements lose the "active" class. When an element has the "active" class, I want the background to change accordingly. If it doesn't have the class, I want to display a different image.

/*  when clicking on item b */
$("#item-b").click(function() {

    $("#content-a, #content-c, #content-d, #content-e, #content-f").hide();
    $("#content-b").removeClass("hidden");
    $("#content-b").show();
    $("#item-b").addClass("active");
    event.preventDefault();

});

if ($("#item-b").hasClass("active")) {
    $('#img-b').attr('src', 'img/img-b-active.png'); /* change image icon */
    $('.section-grey').css("background-image", "url(img/bg-ateliers-cuisine.png)"); /* change background */
    $('#btn-offre').css("background-color", "#ffbf4a"); /* change button color */
} else {
    alert("No active class found"); /* Display another image here */
}

Answer №1

To achieve the desired outcome, you can utilize a mix of CSS and jQuery. It is recommended to assign common classes to the items (icons) for easier selection.

By setting default values in your CSS and altering them in jQuery conditionals, you can toggle between states. For example, changing the src of an image can be done using jQuery while colors and styles can be adjusted using CSS under the .active class.

Refer to the sample code provided below. If you require a more detailed explanation or if there are any misunderstandings, feel free to mention them in the comments section.

$(".item").click(function(event) {

  const otherContent = $(this).siblings().children()
  const thisContent = $(this).children();
  event.preventDefault();
  
  otherContent.hide()
  $(thisContent).removeClass("hidden").show()
  $(this).addClass("active");
  $(this).siblings().removeClass('active')
  
  if (  $(this).is("#item-a")) {
    // do stuff here
    thisContent.css('color', 'pink')
  } else if (  $(this).is("#item-b")) {
    // do stuff here
    thisContent.css('color', 'green')
  } else if (  $(this).is("#item-c")) {
    // do stuff here
    thisContent.css('color', 'purple')
  }
  
});
.item {
  /* no active class */
  background: red;
}

.item.active {
  /* with active class */
  background: blue;
}

.item > div {
  display: none;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item-a" class="item">
  iconA
  <div id="content-a">
    content A
  </div>
</div>
<div id="item-b" class="item">
  iconB
  <div id="content-b">
    content B
  </div>
</div>
<div id="item-c" class="item">
  iconC
  <div id="content-c">
    content C
  </div>
</div>

Answer №2

For scenarios where there is no specific class present, you can implement a condition or add a class as needed. Refer to the code snippet below for guidance.

This issue is elucidated using jQuery and CSS.

$('.det').on('click',function(){
if($(this).hasClass('active')){
$(this).removeClass('active');
}else{
$(this).addClass('active');
}
})
.active{
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="det">click here again and again</div>

<div class='det'>click here again and again</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize Your Lists in Wordpress to Reflect Your Unique Style

I need help with styling a specific text widget in Wordpress by adding a FontAwesome icon as a list bullet. I have the following CSS code: .covenant li { counter-increment: my-awesome-counter; margin: 0.25rem; } .covenant li:before { font-family: 'Fo ...

ajax duplicator and reset form tool

Hello everyone, I have a website where users can add their experiences. While adding an experience, they can dynamically add and remove more fields. One of the input fields is for a date, but when the data is submitted, the same date appears for all entrie ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

The Joys of Delayed Animation with jQuery Isotope

Has anyone successfully modified the CSS3 transitions in jquery Isotope to incorporate a delay for shuffling items, such as using "transition-delay: 0s, 1s;"? I am aiming for a specific shuffle direction - first left, then down - to create a more calculat ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Unusual Behavior of *ngIf and jQuery in Angular 5: A curious case

I'm encountering a strange issue when using the expand-collapse feature of Bootstrap 4 with *ngIf for expansion and collapse. I noticed that the jQuery doesn't work when *ngIf is used, but it works fine when *ngIf is removed. HTML: <div cla ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

"Implementing jquery autocomplete feature with the ability to fetch data from

Currently, I am utilizing jquery's ajax functionality to retrieve data from an external php file. The retrieved data is then intended for use in the autocomplete feature. However, instead of displaying individual values from the array in the php file ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

Identifying changes in value in any scenario, jQuery

When I click on a button and change the input value, I want an alert to display 'Ok Done', but it's not working as expected. The input value may contain both numbers and letters. $("#myTextBox").bind("change paste keyup", function() { ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

Display my search box when the button is activated

I have a button labeled "Search" that I want to click in order for my search field (which is currently hidden with display:none) to become visible. However, my current setup is not working as intended. I have created a jsfiddle to illustrate my issue. Al ...

Obtain personalized results for implementing in Convase JS from a PHP server

I have a table on my WordPress site with the following output: { { [line1]=> array(3) {{'x'=>'5' , 'y'=>'8},{'x'=>'5' , 'y'=>'8},{'x'=>'5' , &apos ...

The synergy between HTML and JavaScript: A beginner's guide to frontend coding

I have primarily focused on server-side development of enterprise applications (Java EE, Spring framework). However, I am now exploring client-side technologies for better understanding (not necessarily to become an expert). I have studied HTML and CSS th ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

Locate the class ID and refine the search results by another class

I am currently working on a task that involves extracting the first <li> element's id where it has the class name my_class, and checking if the <span> with the class Time contains a ":" using jquery. Below is the sample HTML structure: & ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Error: The function execute_script() is expecting between one and two arguments, however three arguments were provided

While attempting to utilize the Selenium method execute_script() in an automated UI test script, I encountered a type error. The error message indicates that there are too many arguments being passed. TypeError: execute_script() takes from 1 to 2 positiona ...