Use jQuery's appendTo function to replace an existing div instead of adding a new one below it

I am facing an issue with this code. I am attempting to add a new div (newGallery) with images to the div (gallery), but it keeps replacing the old one.

Could you please provide some guidance on how to resolve this? I suspect that the problem lies in being inside an ajax function. I am using jQuery v3.5.1.

menu.on('click', 'a', function(event) {
    event.preventDefault();
    
    var a = $(this),
        li = a.parent(),
        href = a.attr('href'),
        loadingImg = $('<img>', {src: 'img/5.svg', class: 'loading-img'}),
        id = '#' + href.slice(0, -5),
        isLoaded = gallery.find(id),
        currentGallery = gallery.find('.gallery-set'),
        galleries = $('.gallery-set');
        
    if (li.hasClass('selected')) return;
    
    li.addClass('selected')
      .siblings().removeClass('selected');
      
    gallery.html(loadingImg).show();
    gallery.find('div').fadeOut();
    
    if ( galleries.attr("id") == id ) {
        currentGallery.hide();
        gallery.find(id).fadeIn();
    } else {
        loadNewGallery(href);
    };
    
    function loadNewGallery (href) {
        var gallery = $('.gallery');
        
        $.ajax({
            url: href,
            data: 'GET',
            dataType: 'html',
        }).done( function( data ) {
            var newGallery = $(data).find('.gallery-set');
            
            newGallery.appendTo(gallery);
            
        }).fail( function() {
            var msg = $('<div>',{class: 'msg-fail'}),
                msgText = 'We apologize, we were unable to display the page',
                msgFail = msg.html(msgText);
                
            gallery.html(msgFail);
            
        }).always(function() {
            loadingImg.hide();
        });
    };
});

Answer №1

Give this method a try...

const imageCollection = $('.image-collection');

function fetchNewImages(url) {
  $.ajax({
    url: url,
    data: 'GET',
    dataType: 'html',
    // If data is loaded, execute the function in done
  }).done(function(data) {
    var newImages = $(data).find('.image-set');

    // The loaded portion of the page via ajax will be permanently added to the image collection
    newImages.appendTo(imageCollection);

    // If data fails to load, execute the function in fail
  }).fail(function() {
    // Message for transfer failure
    var msg = $('<div>', {
        class: 'msg-fail'
      }),
      msgText = 'We are sorry, we could not display the page',
      msgFail = msg.html(msgText);

    imageCollection.html(msgFail);
    // Whether data loads or fails to load, execute the function in always
  }).always(function() {
    // Hide loading icon
    loadingIcon.hide();
  });
};


menu.on('click', 'a', function(event) {
  event.preventDefault();
  var anchor = $(this),
    listItem = anchor.parent(),
    url = anchor.attr('href'),
    loadingIcon = $('<img>', {
      src: 'img/loading.svg',
      class: 'loading-icon'
    }),
    identifier = '#' + url.slice(0, -5),
    isExisting = imageCollection.find(identifier),
    currentImages = imageCollection.find('.image-set'),
    allImages = $('.image-set');

  if (listItem.hasClass('selected')) return;

  listItem.addClass('selected')
    .siblings().removeClass('selected');
  // Show loading icon if content does not load
  imageCollection.html(loadingIcon).show();
  imageCollection.find('div').fadeOut();

  if (allImages.attr("id") == identifier) {
    currentImages.hide();
    imageCollection.find(identifier).fadeIn();

  } else {
    fetchNewImages(url);
  };


});

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

Is it possible to create a database for an HTML website using SQL?

I recently created a simple website with HTML, starting from a basic template. Now I am looking to incorporate SQL to set up a database. My goal is to showcase all the data on the main screen (index.html). Can you provide guidance on how to make this hap ...

Using a SASS watcher to keep an eye on every folder and compile them into a single CSS

I'm interested in setting up a folder structure like this: assets - scss - folder file.scss anotherfile.scss anotherfile.scss anotherfile.scss - anotherfolder file.scss anotherfile.scss anotherfile.scss ...

"Despite receiving a response code of 200 in Rails using jQuery ajax, the data is still

I'm attempting to display a partial in a bootstrap modal. Although I am receiving a 200 response, the JavaScript code within show.haml is not functioning correctly. I have added an alert message for testing purposes, but it does not trigger. In the GE ...

When utilizing JQuery's html() function, it will provide the current contents prior to any modifications made through

I have a div that contains article content which can be dynamically changed using ajax. When trying to retrieve the updated content within this div using the html() function in jQuery, it only returns the content before any changes were made. Is there a ...

Make the active tab stand out in the navigation menu

Could you please advise on how to highlight the active tab in a menu when users switch to another page? This is my current code: .nav { float: left; font-size: 125%; } .nav ul { margin: 0; } .nav li { background: none repeat scroll 0 0 #77 ...

JSON data not displaying correctly in bootstrap table

I've been grappling with this issue for hours now, but I'm struggling to get my bootstrap table populated correctly. Here's the snippet of my HTML: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.1 ...

Optimal alignment of fixed sidebar

I am currently working on making my sidebar sticky on my website . I have implemented a script in the footer that changes the sidebar from a static position to fixed once the page reaches a certain point. The functionality is working correctly, but I am en ...

Formatting for categories of list items

When working with an unordered list, I encountered a challenge where each list item needed to be a specified width. Due to varying text lengths in the list items and the limitations of editing the HTML directly (as I am modifying a template), I turned to a ...

When additional elements follow, the button ceases to function properly in JavaScript

I am working on creating a text-based idle game that involves multiple buttons and text around them. However, I have encountered an issue where the functionality stops working when I try to add text after the "Work" button. The callback function is no lon ...

Screening out specific BBCodes for designated elements

Describing my desired outcome is simple, but as a PHP novice, achieving it proves to be quite challenging. My goal is to streamline BBCodes, making them more concise and easier to use. Instead of using an array like $filter=array( '[b]'=> ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

Keeping Ajax active while the PHP script is running is essential

Seeking assistance with a specific issue. I currently have an ajax script (index.php) that sends variables to a php file (thumbs.php). The php file generates thumbnail images from original files and saves them on the server. This process can sometime ...

"Unleashing the power of infinite Ajax requests upon a drop change event in Knock

I am working with Knockout MVC on my current project and encountering an issue. Whenever I try to pass the viewModel when the Drop Down changes, the method call gets invoked multiple times and the alert message "ok" keeps popping up continuously. Can som ...

The Node.js Express application encountered a TypeError when trying to use the RangeSlider in the Rickshaw.Graph library. The error message received was

Looking for insights on a similar issue as discussed in this Stack Overflow thread about Rickshaw.Graph.RangeSlider TypeError: $(element).slider is not a function The difference with my setup is that I'm utilizing Rickshaw within a node.js applicatio ...

Optimizing Spacing in Twitter Bootstrap 3.1 Nav-stacked Design

Being a novice in HTML coding, I decided to utilize an established API for my project. After some previous experience, I opted to use Twitter Bootstrap 3.1. Here is how my current nav-stacked section appears with a customized CSS to make it collapsible: ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

"Adjusting stacking order with the z-index on the

I have a board where I can drag and drop images, allowing them to be moved around within the board. When an image is dropped onto the board, I use the following code: drop: function (event, ui) { ui.draggable.clone(false) .removeClass('orig ...

How can I make my navbar visible once a specific section has been reached?

Is there a way to conditionally display my navbar in react only when a specific section is reached? Currently, I am monitoring scroll position but this method becomes unreliable on larger screens due to varying scroll positions. I need the navbar to beco ...

I am interested in updating the color of the navigation bar displayed on this website

I am having some trouble with manipulating the appearance of - Specifically, I'm struggling to change the color of the black bar at the top to blue. I have scoured the CSS files and examined the HTML, but I can't seem to locate the relevant code ...

svg stroke-dasharray malfunctioning

I've recently delved into the world of SVG's and I find myself scratching my head over the stroke-dasharray issue. I've scoured the web for answers to no avail, leaving me to believe that I'm overlooking something crucial. Despite imple ...