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>