0

I am trying to fade the content of an article element once clicked and when the fade is complete replace the HTML. Trying to understand why this doesn't work. The code in the fadeOut function doesn't execute.

<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('article').click(function(){
    $(this).find('p').fadeOut(300, function(){
      $(this).html("<p> Glad to see you! </p>");
    }); // end fade
  }); // end click
}); // end ready
</script>
</head>
<body>
<article style="width: 200px; height: 150px; background-color: yellow;">
<p> Hello There </p>
</article>
</body>
ring0
  • 35
  • 1
  • 7
  • Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Sep 16 '21 at 22:39

2 Answers2

0

The reason why it isn't working is because inside the fadeOut function's callback, the "this" refers to the "p" element, and not the ".article".

So it's trying to insert "<p> Glad to see you! </p>" in the "<p>" element which just faded out, and doesn't exist anymore.

Instead you have to add it to the ".article" element. You can keep the "article" element assigned to a variable (here I have assigned it to the variable constant: article), and then use that variable inside the fadeOut's callback to inject the HTML.

<!DOCTYPE html>
<html>
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('article').click(function(){
    const article = this;
    $(this).find('p').fadeOut(300, function(){
      $(article).html("<p> Glad to see you! </p>");
    }); // end fade
  }); // end click
}); // end ready
</script>
</head>
<body>
<article style="width: 200px; height: 150px; background-color: yellow;">
<p> Hello There </p>
</article>
</body>

</html>

If you would like to learn more on the "this" keyword and how it works, I recommend visiting here.

Chique
  • 735
  • 3
  • 15
0

Consider the following.

$(function(){
  $('article').click(function(){
    var $self = $(this);
    $("p", this).fadeOut(300, function(){
      $self.html("<p> Glad to see you! </p>");
    });
  });
});

This removes any ambiguous this references.

Twisty
  • 30,304
  • 2
  • 26
  • 45