Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method along with the .find() method. However, when I try to introduce a delay into the function responsible for finding and replacing the innerHTML content, the functionality ceases to work. Below is the code that I have developed thus far:

The '#current-title' refers to the element whose content needs to be replaced; while '#title1' contains the text that should be inserted into '#current-title'. The entire process should include a smooth transition of opacity change for '#current-title' before and after the text replacement.

$(document).ready(function() {
  $.replace = function() {

  $('#current-title').css("opacity", "0");

  setTimeout(function() {
    $('#current-title').html($(this).find('#title1').html());
  }, 500);

  setTimeout(function() {
    $('#current-title').css("opacity", "1");
  }, 1000);

  alert('Title has been replaced.');
  };

  $(".replace-btn").click(function() {
    $.replace();
  });
});

A simplified version of the same function, which simply replaces the html of '#current-title' without utilizing a setTimeout, functions perfectly fine:

$(document).ready(function() {
  $.replace = function() {

    $('#current-title').html($(this).find('#title1').html());

    alert('Title has been replaced.');
  };

  $(".replace-btn").click(function() {
    $.replace();
  });
});

Why does the setTimeout in my initial block of code fail to work?


$(document).ready(function() {
  $.replaceDelayed = function() {

    $('#current-title').css("opacity", "0");

    setTimeout(function() {
      $('#current-title').html($(this).find('#title1').html());
    }, 500);

    setTimeout(function() {
      $('#current-title').css("opacity", "1");
    }, 1000);

    setTimeout(function() {
      alert('Title has been replaced.');
    }, 1000);
  };

  $(".replace-btn").click(function() {
    $.replaceDelayed();
  });
});


$(document).ready(function() {
  $.replaceNormal = function() {

    $('#current-title').html($(this).find('#title1').html());

    alert('Title has been replaced.');
  };

  $(".replace-btn2").click(function() {
    $.replaceNormal();
  });
});
.title {
  visibility: hidden;
}

* {
  transition: opacity 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-title">
  <a>Project Title #0</a>
</div>

<br>

<div class="title" id="title1">
  <a>Project Title #1</a>
</div>

<br>

<button class="replace-btn">
  Replace Title (with delay)
</button>

<button class="replace-btn2">
  Replace Title (without delay)
</button>

Answer №1

Here is a quick demonstration using jQuery.fadeOut followed by jQuery.fadeIn:

$(document).ready(function() {
  var counter = 0;
  $( "p" ).click(function() {
    ++counter;
    $this = $(this);
    $this.fadeOut(500, function() {
      $this.html("New Project #" + count);
      $this.fadeIn(500);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>New Project #0</p>

Try the code snippet and see how each click on the project title causes it to fade out, increase its number, and then fade back in.

Answer №2

If you remove setTimeout from your code, the object that this refers to is the window. The method window.find will look for a string in the current window and not search for an element in the document. You can refer to this link for more information.

The context of this within the setTimeout method returns a function object.

After removing this, your code will work properly.

This updated code snippet should work correctly:

$(document).ready(function() {
  $.replaceDelayed = function() {

    $('#current-title').css("opacity", "0");

    setTimeout(function() {
      //console.log(this) returns the window object
      $('#current-title').html($('#title1').html());
    }, 500);

    setTimeout(function() {
      $('#current-title').css("opacity", "1");
    }, 1000);


  };

  $(".replace-btn").click(function() {
    $.replaceDelayed();
  });
});


$(document).ready(function() {
  $.replaceNormal = function() {
    //console.log(this); returns a function object
    $('#current-title').html($('#title1').html());

    alert('Title has been replaced.');
  };

  $(".replace-btn2").click(function() {
    $.replaceNormal();
  });
});
.title {
  visibility: hidden;
}

* {
  transition: opacity 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-title">
  <a>Project Title #0</a>
</div>

<br>

<div class="title" id="title1">
  <a>Project Title #1</a>
</div>

<br>

<button class="replace-btn">
  Replace Title (with delay)
</button>

<button class="replace-btn2">
  Replace Title (without delay)
</button>

Answer №3

$(document).ready(function() {
  $.replaceDelayed = function() {

    $('#current-title').css("opacity", "0");

    setTimeout(function() {
      $('#current-title').html($(document).find('#title1').html());
    }, 500);

    setTimeout(function() {
      $('#current-title').css("opacity", "1");
    }, 800);

    setTimeout(function() {
      alert('Title has been replaced.');
    }, 1000);
  };

  $(".replace-btn").click(function() {
    $.replaceDelayed();
  });
});


$(document).ready(function() {
  $.replaceNormal = function() {

    $('#current-title').html($(document).find('#title1').html());

    alert('Title has been replaced.');
  };

  $(".replace-btn2").click(function() {
    $.replaceNormal();
  });
});
.title {
  visibility: hidden;
}

* {
  transition: opacity 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-title">
  <a>Project Title #0</a>
</div>

<br>

<div class="title" id="title1">
  <a>Project Title #1</a>
</div>

<br>

<button class="replace-btn">
  Replace Title (with delay)
</button>

<button class="replace-btn2">
  Replace Title (without delay)
</button>

Here $(this) refers to the Window Object. To get a handle, you need to use the $(document) object

Give this approach a try

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 am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Why aren't my messages showing up once I exit the textbox on my website?

After writing various functions to compare two passwords, I encountered an issue. My goal was for the message "The passwords match" or "Please enter your password again because the two passwords don't match" to be displayed when clicking out of the "v ...

What could be causing my scrollable div to not function properly within a Bootstrap modal?

I am facing a frustrating issue. I have a simple DIV element that I want to make scrollable, containing a table inside it. The process should be straightforward as I have a separate .html file with the code that functions correctly. Here is an excerpt of ...

Toggling siblings in jQuery when focusing and blurring

Currently, I have this setup that seems to be functioning well. However, I am looking for an optimal way to write it as I am creating a mobile site where performance is crucial. Imagine a tooltip that slides down (toggles) under the element. There are app ...

JSONP Error - "SyntaxError: Unexpected token caught"

Just to start off, I want to mention that I'm new to working with jsonp. This is my first time diving into the world of JSONP. Currently, I'm using a jQuery ajax call to retrieve data from a website. Here's a snippet of my jQuery code: $. ...

Utilizing margins in CSS for various div elements

Update: I have included Javascript and Masonry tags in my project. Despite having modules of the same size, I am exploring how masonry can assist me. However, I find it a bit puzzling at the moment as I am not aiming to align elements of different sizes. I ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

When troubleshooting AJAX in Chrome, only the library lines are displayed in the call stack

While using "XHR breakpoints" to identify which line is triggering an AJAX request, I noticed that the call stack only shows Angular.js library lines. This makes it difficult to pinpoint the exact line in my code that triggered the request. What steps shou ...

Mixing strings with missing slashes in links

console.log(mylink) When using the console to log mylink, the expected result is a normal link like http://example.com/something.jpg. I tried concatenating it as shown below: var html = '<div id="head" style="background:linear-gradient(rgba(0, 0 ...

Revising the input to adjust the variable, which will then update the table

I'm currently working on a project that involves creating a basic table where users can input a registration number and have the corresponding car name displayed in the adjacent cell. While using variables and writing the if statement, I've enco ...

Functionality in Three.js that involves selecting nearby objects with an event handler and ensuring that the self object is

I have spent countless hours today diving deep into the documentation, tutorials, and stackoverflow questions in pursuit of a solution to this issue. I am pleading for your assistance – please take pity on me and help! The problem at hand involves a wat ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

Extracting the inner content in the absence of an HTML element, only plain text

My website's platform has some unusual HTML that I need to work with. There is a section of code that looks like this: <div class="report-description-text"> <h5>Description</h5> Welcome to Ushahidi. Please replace this report with a ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Whenever I utilize paesrInt in the POST request, an error occurs. I have included the code below for reference

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.get("/", function (req, res) { res.sendFile( ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Tips for implementing pagination in a search result by adjusting the skip and limit values within the same query

While some may argue that this question belongs on programmers.stackexchange.com, after reviewing the Help Center of Stack Overflow, I believe it is a specific programming issue and will likely receive a better response here. I have developed a webapp usi ...