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

The difference between using an event listener directly in HTML vs. using the add

Looking to customize the behavior of an HTML element using event listeners? There are two ways to accomplish this: <form class="my-form"> <input type="submit"/> </form> <script> document.querySelectorAll(&quo ...

Troubleshooting: Issue with Ajax Post Request in Django Version 1.10.5

For the past week, I've been facing difficulties in successfully executing a jQuery ajax request to transfer data from a JavaScript function within my annualgoals.html file to a Django view for database storage. Currently, I'm just trying to veri ...

Determine the remaining load time in PHP after submitting a task

Is there a way to incorporate a progress bar that displays the percentage while "preparing the next page" before redirection? I have successfully implemented the progress bar animation, but now I am looking for an approximation of the time it will take be ...

Using Jquery variables for calculations and they do not work with numerical values

Hey there, I'm new to this so bear with me. I have a jQuery question that's puzzling me... I'm attempting to set the line height using the following method: var line_height = $('.container').css("height"); console.log(line_height ...

Centered Tailwind CSS logo design

Here is my current fiddle: https://jsfiddle.net/w5c36epd/ Upon close inspection, you may notice that the logo is not properly centered. I have experiment with various flexbox options such as: <div class="flex-shrink-0 justify-center"> ...

Leveraging the power of Google Closure Templates alongside the versatility of

We are embarking on developing an application using JavaScript and HTML5 that will utilize a rest API to access server resources, leveraging the power and convenience of jQuery which our development team is already proficient in. Our goal is to make this a ...

Storing a JSON object within a data attribute in HTML using jQuery

In my HTML tag, I am storing data using the data- method like this: <td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td> When retrieving the data in a callback, I use: $(this) ...

What is the best way to display content at a specific time using Angular?

Whenever a user searches something and no results are found, I display a message. However, when there is content to show, an error message pops up for about 3-4 seconds before disappearing and showing the search results. This is my HTML: <div> &l ...

Is the hover rotation feature not functioning properly?

I am trying to achieve a small rotation effect when I hover over my div. It works perfectly on another div, but for some reason it's not working on this one. Below is the code snippet: .more, .more:visited { color: #fff; min-width: 88px; heigh ...

CakePHP allows developers to easily include images in their links using the `$this->Html->link` method. However, instead of generating HTML code for the image, it outputs ASCII characters

I can't seem to find the solution in the CakePHP 2.3.0 manual. I am trying to use $this->Html->link with $this->Html->image to create a clickable image. However, I'm encountering an issue where the ASCII rendering of quotes is being g ...

Problems with displaying Wordpress content on your web browser

I am having trouble getting my website content to display properly in a web browser, even though I built it using Wordpress. It appears that only the logo and the 'Services' bar are showing up on the page, while the rest seems to be missing. I s ...

Is it possible to utilize :not in this scenario?

<ul class="promocode"> <li>one</li> <li>two</li> <li class="three">three</li> </ul> Is there a way to use :not in order to apply a hover effect to the entire list, except when hovering ov ...

Utilizing MUI for layering components vertically: A step-by-step guide

I am looking for a way to style a div differently on Desktop and Mobile devices: ------------------------------------------------------------------ | (icon) | (content) |(button here)| ----------------------------------------- ...

In order to comply with JSX syntax rules in Gatsby.js, it is necessary to enclose adjacent elements

I want to apologize beforehand for the code quality. Every time I attempt to insert my HTML code into the Gatsby.js project on the index.js page, I encounter this error: ERROR in ./src/components/section3.js Module build failed (from ./node_modules/gatsb ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

The sub-menu options are constantly shifting... How can I keep them in place?

Here we go again... I'm having trouble with my sub-menu elements moving when I hover over them. I've searched for a solution but haven't found anything helpful. The previous advice I received about matching padding and adding transparent bo ...

Numerous options available in a dropdown menu

I have a Dropdown menu that offers various functions. "Update" option redirects to a page for updating information "Export Form" option redirects to a page for exporting the form Although the current code allows these actions, I am facing an issue with ...

Add a specific class to an element when it has a child within it

I am facing an issue where I need to apply a special class to elements with the same class if they have a specific child element. Here is what I have attempted: if ( $('li.first_li').find('ul.multi-menu') ) alert('code'); T ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...

AngularJS Input field fails to update due to a setTimeout function within the controller

I am currently working on a project that involves AngularJS. I need to show a live clock in a read-only input field, which is two-way bound with data-ng-model. To create this running clock effect, I am using a JavaScript scheduler with setTimeout to trigge ...