Add HTML or append a child element when clicking, then remove it from the previously clicked element

Within a container, I have several div elements where .div-to-hide is shown by default and .div-to-show is hidden.

My goal is to toggle the visibility of these elements - when clicking on a .set, .div-to-hide should hide and .div-to-show should become visible. Subsequent clicks should revert the previously clicked element to its original state.

Additionally, I want to display two buttons inside each .div-to-show.

<div class="container">
  <div class="set">
    <div class="div-to-hide">Some text</div>
    <div class="div-to-show"></div>
  </div>
  <div class="set">
    <div class="div-to-hide">Some text</div>
    <div class="div-to-show"></div>
  </div>
  <div class="set">
    <div class="div-to-hide">Some text</div>
    <div class="div-to-show"></div>
  </div>
</div>

This is my current code snippet:

let lastClicked;
$('.container').on('click', function(e) {
  if (this == lastClicked) {
    lastClicked = '';
    $('.div-to-hide').show();
    $(this).children('.div-to-hide').hide();
  } else {
    lastClicked = this;
    $('.div-to-hide').hide();
    $(this).children('.div-to-hide').show();
    $(this).children('.div-to-show').hide();
  }
});

I'm facing some issues with making it work as intended. Any assistance would be greatly appreciated!

UPDATE: I managed to fix it! Thanks for all the help!

Answer №1

To start off, it appears that you are not utilizing delegation (the second parameter on the $.on() function) to specify the .set element as your current context (this) within the function.

If my understanding is accurate, your objective is to display the elements corresponding to the last clicked item while hiding the others. It's worth noting that knowing the exact last clicked element may not be necessary for achieving this.

$('.container').on('click', '.set', function (e) {
    // At this point, "this" refers to the clicked .set element
    var $this = $(this);
    // We identify the specific children of .set that we would like to manipulate
    var $div_to_hide = $this.find(".div-to-hide");
    var $div_to_show = $this.find(".div-to-show");

    // If the targeted section is already visible, no further action is required
    if ($div_to_show.is(":visible")) {
        $div_to_hide.show();
        $div_to_show.hide();
    }

    // Now let's select the other .sets 
    var $other_sets = $this.siblings(".set");

    // Alternatively, consider this method for handling more complex hierarchies. Uncomment if needed
    // var $other_sets = $this.closest(".container").find(".set").not(this);

    // We reset ALL other sets
    $other_sets.find(".div-to-show").hide();
    $other_sets.find(".div-to-hide").show();
});

Answer №2

Consider utilizing class toggling as an alternative method.

$('.set').on('click', function(e) {
  $('.set').removeClass('hidden-child');
  $(this).addClass('hidden-child');
});

CSS:

.hidden-child .div-to-hide, .div-to-show {
  display: none;
}
.hidden-child .div-to-show, .div-to-hide {
  display: block;
}

This approach will enhance the clarity and logic of your code, allowing the CSS to manage the display rules effectively.

Edit: Adjusted class name for better understanding; provided further explanation; ensured answer alignment with question requirements

Answer №3

Utilize siblings() jQuery function to alternate the visibility of other divs and leverage toggle() jQuery method to display or hide itself. Additionally, ensure to apply the click() event on the .set class instead of the .container.

$(document).on('click', '.set', function(e) {
  $(this).find('.hide').toggle();
  $(this).find('.show').toggle();
  $(this).siblings('.set').find('.hide').show();
  $(this).siblings('.set').find('.show').hide();
});
.show {
  display: none;
}

.set div {
  padding: 10px;
  font: 13px Verdana;
  font-weight: bold;
  background: red;
  color: #ffffff;
  margin-bottom: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="set">
    <div class="hide">1 Hide</div>
    <div class="show">1 Show</div>
  </div>
  <div class="set">
    <div class="hide">2 Hide</div>
    <div class="show">2 Show</div>
  </div>
  <div class="set">
    <div class="hide">3 Hide</div>
    <div class="show">3 Show</div>
  </div>
</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

Strange Behavior of Zoom DIV Effect during Rapid Hovering

Here is the code I am working with: http://jsfiddle.net/8fvJN/15/ Whenever I try to quickly hover from one box to the next, a strange effect occurs where they start behaving erratically. If you hover between boxes rapidly, you will observe this behavior. ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

Responsive Design and Advertising with CSS Media Queries

For my application, I am utilizing Twitter's bootstrap (responsive) css. My goal is to incorporate banner ads in the sidebar section. However, due to different media query settings, the sidebar's width will vary, resulting in the need for the ban ...

How do I use jQuery to target a specific list item based on its data attribute and the ID of the list it belongs to?

Can anyone provide me with the correct jQuery syntax for selecting a list item based on a data attribute within a specific list? Below is an example list: <ul id="menu"> <li data-code="soup">Soup</li> <li data-code="salad">Salad< ...

Prevent multer from uploading files if the field is left blank

Is there a way to prevent multer from attempting to upload a file if a specific field is left blank in a post request for users to update their profile? For example, if a user only wants to update their bio and not their profile picture. Here's the c ...

AngularJS data retrieval timeout function

After reading this response, I am currently in the process of developing a service that can provide data even if the request fails due to timing out. this.getStatus = function() { var timeoutPromise = $timeout(function () { cancele ...

Utilizing BeautifulSoup for Web Scraping (handling missing values during the scrape)

I have been facing two challenges while trying to scrape data from a realtor website using BeautifulSoup. These issues have proven to be quite tricky: Challenges: After running my code snippet, I noticed that some date values are missing in the dataframe ...

a guide on incorporating PHP variables into Bootstrap Full Calendar

While using the full calendar in Bootstrap from this source, I am facing an issue. Instead of passing the PHP variable like 'start: new Date(y, m, d, 8, 30),' I want to pass the value of y instead of $y and m instead of $m. How can I achieve this ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

The CSS animation will run infinitely, but the desire is for it to only complete one iteration

My div element is set to animate by increasing in width and opacity over an image. However, I only want it to run once but it seems to loop infinitely. Can anyone help me achieve a single iteration? Thank you! Here is the markup: <div class="capback"& ...

Is it possible to automatically adjust the size of components on a html/cshtml page based on the current window size?

Currently, I am facing an issue with my website where multiple panels are created using a foreach loop that includes textareas/textboxes. Whenever I resize my browser window, it messes up the UI by shifting the position of the textareas and other elements. ...

The battle between Hover, Focus, and Blur modes intensifies

My goal is to implement 4 different effects on an element: When hovering over the element. When moving away from the element. When focusing on the element. When blurred. However, I'm encountering a conflict where when I focus on the element, the ...

Customize React JS Material UI's InputBase to be responsive

https://i.stack.imgur.com/9iHM1.gif Link: codesandbox Upon reaching a certain threshold, like on mobile devices, the elements inside should stack vertically instead of horizontally, taking up full length individually. How can this be achieved? ...

Having trouble displaying my klout score with ajax

I'm attempting to showcase a Klout score on a webpage Here's my code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var settings = { "url": "http://api.klout.co ...

Highcharts Date Confusion

My JSON data includes timestamps and values like: [ [1230768000,2], [1233446400,3], [1235865600,2], [1238544000,6], [1241136000,1], [1243814400,2], [1246406400,7], [1249084800,3], [1251763200,5], [1254355200,2], [1257033600,5], [1259625600,4] ] The dates ...

Issue with Datepicker functionality within the <th> element is causing it to malfunction

Currently, I am attempting to utilize the Bootstrap datepicker, but I am facing an issue when trying to implement it within a table, specifically inside a th element. Below is the structure of my table: <table id="table" class="table table-bord ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

Creating a masonry layout with uniform row heights

I am trying to achieve a masonry style layout for these cards in Bootstrap. The current setup has columns with the same height, but I want them to have fluid height and consistent margin spacing like the blue line shown below. I attempted to use .card-colu ...

Different approach to reach AngularJS isolated scope

Utilizing AngularJS isolated scope is an effective method for creating reusable components within angular directives. I find it to be quite beneficial. There are occasions when access to child scopes is necessary for data manipulation or method invocation. ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...