One way of prepending html with jquery works but why the other way doesn't?
-
27-10-2019 - |
Question
This way of prepending does work for me:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#learn-more-button").click(function() {
$("#main-text").load('ajax/learn-more.html #learn-more', function() {
$(this).prepend('<p> DARN </p>'); // <=== This here WORKS
$(this).hide().fadeIn(500); //Fade in
$("#main-text").animate({ // Then Animate
width:"500px",
left:'+=400px',},
400
);
});
});
});
</script>
This way of prepending doesn't work for me:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#learn-more-button").click(function() {
$("#main-text").prepend('<p> DARN </p>'); // <=== This here doesn't work
$("#main-text").load('ajax/learn-more.html #learn-more', function() {
$(this).hide().fadeIn(500); //Fade in
$("#main-text").animate({ // Then Animate
width:"500px",
left:'+=400px',},
400
);
});
});
});
</script>
Why the second way doesn't work? How should it be done to make it work?
I'm not really a jQuery guy, so help is appreciated :)
Solution
When you perform the load()
the contents of the #main-text
element are completely replaced. Therefore if you add the <p>DARN</p>
before the load
- as in the second method, it gets overwritten.
In the first method the <p>
is being added in the callback function of the load. This is called after the load has been completed.
You should also chain methods on to one selector for better performance, like this:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#learn-more-button").click(function() {
$("#main-text").load('ajax/learn-more.html #learn-more', function() {
$(this).prepend('<p> DARN </p>')
.hide().fadeIn(500)
.animate({
width:"500px",
left:'+=400px'
}, 400);
});
});
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow