The jQuery remove function will only take effect on the second click following an AJAX request

I'm facing an issue with my jQuery code where two divs contain lists of links, triggering AJAX calls to append JSON data to a separate div. Upon clicking a link, the corresponding link div should hide. There's also a third div with the class "panel-close" that resets the view by removing the appended data and showing the link div again.

The problem arises when sometimes the link div does not reappear after removing the data container, or the JSON data fails to append on subsequent clicks. Here is the basic structure of my HTML:

<div class="curation-panel">
  <div class="curation-contents-list">
    <a class="load-article"></a>
  </div>

  <div class="article-container"></div>
</div>

<div class="film-panel">
  <div class="film-contents-list">
    <a class="load-project"></a>
  </div>

  <div class="project-container"></div>
</div>

<div class="panel-close"></div>

Below is the jQuery code I've implemented:

$(function(){
  var element = $('.load-article');
  var url     = element.data('page') + '.json';
  var target  = $('.article-container');

  $(element).on('click', function(e) {
    e.preventDefault();

    $.get(url, function(data) {
      $('.curation-contents-list').hide();
      $(target).append(data);
    });
      $("body").addClass("load-article-is-open"),
      $(this).animate({
          scrollTop: 0
      }, 300, "easeInOutExpo")

  });
}),

$(function(){
  var element = $('.load-project');
  var url     = element.data('page') + '.json';
  var target  = $('.project-container');

  $('.load-project').on('click', function(e) {
    e.preventDefault();

    $.get(url, function(data) {
      $('.film-contents-list').hide();
        $(target).append(data);
    });
      $("body").addClass("load-project-is-open"),
        $(this).animate({
            scrollTop: 0
        }, 300, "easeInOutExpo")
  });
}),

$(".panel-close").click(function() {
    $("body").removeClass("curation-panel-is-open").removeClass("film-panel-is-open").removeClass("load-article-is-open").removeClass("load-project-is-open"),
    $(".curation-panel").animate({
        scrollTop: 0
    }, 300, "easeInOutExpo"),
    $(".film-panel").animate({
        scrollTop: 0
    }, 300, "easeInOutExpo"),

    $('.curation-contents').show();
    $('.film-contents-list').show();
    $('.article-container').remove();
    $('.project-container').remove();
});

Answer №1

You make a reference to an element that you later add the results of an Ajax call to

var destination = $('.content-box');

The issue arises when you remove these elements here:

$('.content-box').remove();
$('.section-container').remove();

Once they are removed, any code trying to access them will not be able to find them.

I suggest using empty() instead of remove() in this case.

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

I attempted to access data from the phpmyadmin database, but the browser is displaying an error message stating "cannot get/employee", while there are no errors showing in the command prompt

const { json } = require('express/lib/response'); const mysql=require ('mysql'); const express=require('express'); var app=express(); const bodyparser=require('body-parser'); app.use(bodyparser.json()); var mysq ...

Problem with Google Chart formatting

I currently have a Line chart displaying the Y axis as 20,000,000 and I would like to change the format to 20K. How can I modify the format in a Google chart? Any assistance is greatly appreciated. Code: <html> <head> <script type=" ...

Minimizing the size of a production application's bundle

In a production application I am working on, the bundle size is currently 8.06MB. # Output from npm build File sizes after gzip: 1.67 MB build/static/js/3.73cf59a2.chunk.js 794.29 KB build/typescript.worker.js 131.13 KB build/css.worker.js 1 ...

What is the best way to calculate the total duration (hh:mm) of all TR elements using jQuery?

I currently have 3 input fields. The first input field contains the start time, the second input field contains the end time, and the third input field contains the duration between the start and end times in HH:mm format. My goal is to sum up all the dur ...

Once chosen, zoom in on the map to view the results

I am facing an issue with multiple selects in my code, where one select depends on the result of another. The ultimate goal is to zoom in on the area that has been searched and found, but unfortunately, it is not functioning as expected. If you'd lik ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

The image displayed on the HTML scrset attribute is not the correct one

I'm experiencing an issue with correctly loading the responsive image using scrset. The sizes attribute I am using is: sizes="(max-width: 767px) 95vw, 768px" and for the srcset attribute: srcset="https://cdn.runningshoesguru.com/wp-content/uploads ...

Utilizing Jquery Tooltipster to Interact with DOM Elements Post-AJAX

I've been encountering some issues with the Tooltipster jQuery plugin and AJAX: Clicking on a link to launch Tooltipster works fine Receiving a form through AJAX is also successful However, I am unable to interact with the input fields in my form Be ...

Is there a way to create a table with "cells that can be controlled individually" similar to the image provided using HTML and CSS?

I have been searching online for solutions on how to create a table similar to the one in this image, but so far I haven't had much luck. I attempted to use colspan, however, it didn't yield the results I was hoping for. Does anyone have any alt ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...

What is the interaction between Vue's v-model and the update:modelValue directive, and how can we customize the default behavior to prevent it from

Could someone provide an explanation of the usage of v-model with :modelValue and update:modelValue? What happens when both are used together? In the code snippet below, a component is shown: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3. ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

Sending Objects Array in POSTMAN using Hapijs: A Step-by-Step Guide

Could you please assist me on how to send a POST request in POSTMAN for the given array of objects and then validate it using Joi in a hapi server? var payload = [{ name: 'TEST Name 1', answer: 'TEST Answer 1', category: &a ...

What am I doing wrong that causes me to repeatedly run into errors when trying to build my react app?

While attempting to set up a react.js web application in VScode using "npm," I encountered the following errors: npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Invalid response body while trying to fetch https://registr ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

Dimension of the element that has been positioned absolutely

One of my challenges involves working with an absolutely positioned div element (.tooltip) containing another div (.text) that has text with a set max-width. The issue arises when the left property of .tooltip is too large, causing its width to shrink du ...

Using Ant Design with Formik to dynamically set field values in a form

When I click the "Change" button in an Antd table with data, the entire line of data is passed to a function as an object. However, I am having trouble inserting the data into the fields. What should I do? How can I set data to Antd input using an externa ...

400 Error: Frustrating AJAX POST Request Woes

Attempting to send data to a controller using the POST method with jQuery AJAX. Below is the code being used: $('#save_new').on('click', function () { var category_name = $('#new_category').val(); ...

Deleting an HTML column that has a dynamic header name <th> can be achieved by following these steps

I have a script that can add a new column to an HTML table. When the user clicks on add group, the header will change to Group1, Group2, and so on. I am currently adding a function for delete group that can delete all the added columns. The issue now is th ...