Attempting to change the src of a different image using jQuery upon clicking

I have two separate divs that change their background image source when clicked, which is working fine. However, I would like them to change the other image they are paired with. For example, if div 1 is clicked and becomes "open", then if div 2 is "open" it should become closed. My knowledge of jQuery is limited, and while I can change the image, I need to figure out how to apply the "closed" class to images that haven't just been clicked. Ideally, I would like to use attr() so that I can add more functionality later.

jQuery

$(".box").on("click", function() {
      
      // need to make this function select the other div.
      if ($(this).hasClass("closed")) {
        $(this).addClass("open").removeClass("closed");
      } else {
        $(this).addClass("closed").removeClass("open");
      }
      
      var id = $(this).attr("data-id");
      $(this).toggleClass("open");
      $(".hideDivs").hide();
      $("#" + id).show();  
    });
 .container {
      width: 640px;
      height: 450px;
      background-color: #eee;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
    }
    
    .text-primary {
      font-size: 14px;
      text-align: center;
      margin-bottom: 5px;
    }
    
    .box {
      cursor: pointer;
      width: 90px;
      height: 180px;
      display:block;
      margin:auto;
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }
    
    .open {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/open_ihcmuz.png");
    }
    
    .closed {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }
    
    .hideDivs {
      display: none;
    }
    
    .panel-body {
      padding: 10px;
      margin-top: 5px;
    }
    
    .title {
      font-weight: bold;
      font-size: 14px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
      <div class="row">
        <div class="col-xs-6">
          <div class="box" data-id="divId1">
          </div>
        </div>
        <div class="col-xs-6">
          <div class="box" data-id="divId2">
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <div class="panel panel-default hideDivs" id="divId1">
            <div class="panel-body">
              <span class="title">Practices for safe packaging of cooked foods</span>         
              <ul>
                <li>Label and date all food.</li>
                <li>Package high-risk food in small batches for refrigeration and return to refrigerated storage as soon as possible (within 20 minutes).</li>
                <li>Store packaging products in a clean environment and protect from contamination.</li>
              </ul>          
            </div>
          </div>
          <div class="panel panel-default hideDivs" id="divId2">
            <div class="panel-body">
              <span class="title">Practices for safe freezing of cooked foods</span>
              <ul>
                <li>When packaging food for freezing, cover or wrap, label and date (production and freezing date) all foods.</li>
                <li>Freeze food in small quantities to ensure food is frozen quickly.</li>            
                <li>Do not overload freezer units and ensure air can circulate.</li>
                <li>Do not freeze foods that have been cooked then refrigerated and reheated.</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>

Answer №1

Feel free to take a look at the jsfiddle and let me know if this is what you had in mind. Here's the link to the jsfiddle.

When a box with a specific data-id is clicked, it toggles between open and closed states and shows a corresponding div. If another box is clicked, it will toggle the previous one and show the new div.

$(".box").on("click", function() {
    var id = $(this).attr("data-id");
    if( id === 'divId1') {
        $('div[data-id="divId2"]').addClass('closed').removeClass('open');
    } else {
        $('div[data-id="divId1"]').addClass('closed').removeClass('open');
    }

    // need to make this function select the other div.
    if ($(this).hasClass("closed")) {
        $(this).addClass("open").removeClass("closed");
    } else {
        $(this).addClass("closed").removeClass("open");
    }
    $(".hideDivs").hide();
    $("#" + id).show();  
});

Answer №2

Here is an alternative approach to consider:

$(".box").on("click", function() {
    // Hiding all detail divs
    $(".hideDivs").hide();

    if ($(this).is(".closed")) {
        // Closing other open boxes
        $(".box.open").removeClass("open").addClass("closed");
        // Opening this box and displaying the corresponding details div
        $(this).removeClass("closed").addClass("open");
        var id = $(this).attr("data-id");
        $("#" + id).show();  
    } else {
        // Closing this box
        $(this).removeClass("open").addClass("closed");
    }

});

Additionally, it is suggested to update your HTML so that your 'box' elements also possess a 'closed' class, eliminating the necessity to repeat the CSS background attribute on the 'box' class.

View the functionality in action at this fiddle

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

Operating a slider on a web page built with HTML

I am currently working on developing a loan calculator that involves two range sliders interacting with each other to display monthly payments in a label. Here are the specific requirements: Display only 5 values on the "Month" range slider: 12,18,24,30,3 ...

How to unselect a radio button in Vue using a button, similar to using vanilla JavaScript

Looking to translate this vanilla JavaScript code into Vue, here's the original: const radio = document.querySelector('#radio'); const boton = document.querySelector('#boton'); boton.addEventListener('click', () => { ...

When navigating to an external dialog, the rounded corners are no longer visible after changing the page

When using JQuery Mobile 1.3.1 to load an external view into the DOM using $.mobile.changePage, I ensure that the correct options are used to load the view as a dialog. However, I am facing an issue where the rounded corners on the dialog seem to disappear ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

Developing real-time chat functionality in React Native with node.js and Socket.io

I'm on the lookout for resources to help me navigate both server-side (mostly) and client-side development. I recently came across a resource called Simple Real Time chat app but unfortunately, it did not yield significant results. I tried locally ho ...

Creating a custom JavaScript library using an existing npm module (codius)

Embarking on a new journey with this, never tried it before. Currently utilizing https://github.com/codius/codius-host. The development of Codiu§ has been abandoned, however I am determined to salvage some parts of it for my own project. It is crucial fo ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

What is the method for inserting form control values into a QueryString within HTML code?

Struggling with passing HTML form control values into a QueryString for page redirection. While I can easily input static values into a QueryString and retrieve them using PHP's GET method, I am encountering difficulties when it comes to dynamic valu ...

Initiate a POST ajax request to retrieve the file.Let's

I'm currently working on an Asp.Net MVC project and I have a piece of code in my View that looks like this: $.ajax({ beforeSend: function () { LoadStart(); }, complete: function () { LoadStop(); ...

When using Angular 8 with RxJs, triggering API calls on click events will automatically detach if the API server is offline

I have an Angular 8 application with a form containing a save button that triggers a call to a Spring Boot microservice using RxJs. I decided to test what would happen if the Rest API server were down. When the Rest API is running, clicking the button wor ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before. My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behav ...

Using Angular 2 to toggle visibility based on a select box's value

<div class="form-group"> <label class="col-md-4 control-label" for="is_present">Is Present?</label> <div class="col-md-4"> <select id="is_present" name="is_present" class="form-control" *ngIf="candidates.is_present === tr ...

Error 404 in Cordova AJAX请求

As I work on developing an android application with cordova, AJAX requests are essential for the functionality. Utilizing jQuery for these requests, I updated the security policies in index.php to allow connection to a remote server. However, upon initiati ...

Leveraging Webworkers in an Angular application for efficient data caching with service workers in the Angular-CLI

I am looking to run a function in the background using a worker, with data coming from an HTTP request. Currently, I have a mock calculation (e.data[0] * e.data[1] * xhrData.arr[3]) in place, but I plan to replace it with a function that returns the actual ...

Ways to use CSS to align a table row to the right

I've been attempting to shift the alignment of a table row that contains the navigation links for my website from left to right, but no matter what I try to modify, nothing seems to budge. I'm relatively new to studying HTML and CSS, so I would g ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

Is it possible to prevent the text from appearing in the text box when a button is

I have successfully implemented a feature where clicking on the button (click on me) in HTML displays a textbox along with another button (show) on the screen. The text written in the textbox is visible when the show button is clicked. However, after the i ...