Jquery using (this) in a user-defined function

I created a small jquery script, and I have a problem using (this) in a user-defined function.

This is the code:

jQuery("li").click(function() { var scrollTop = jQuery(window).scrollTop(); if(scrollTop > 0) { jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function() { fadeItems(); }); } else { fadeItems(); } }); function fadeItems() { var slogan = jQuery(this).children('p').html(); jQuery('#slogan_text').fadeOut(150, function(){ jQuery('#slogan_text').fadeIn(150).html(slogan); }); var content = jQuery(this).children('#post_content_large').html(); jQuery('#content_view').html(content).hide(); var status = jQuery("#readMore").html(); if(status == 'Verbergen') { jQuery('#content_view').fadeIn(500, function(){ jQuery('#content_view').fadeIn(500).html(content); }); } var title = jQuery(this).children('h3').html(); jQuery('#title_content').fadeOut(150, function(){ jQuery('#title_content').fadeIn(150).html(title); }); } 

Thus, the function starts when you click on the list items and goes kindly, but the values ​​(this) are empty

Does anyone know how to fix this?

Thanks in advance!

+6
source share
3 answers

.call can be useful here:

 jQuery("li").click(function () { var self = this; var scrollTop = jQuery(window).scrollTop(); if(scrollTop > 0) { jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function() { fadeItems.call(self); }); } else { fadeItems.call(self); } }); 
+2
source

Because you have to pass it to a function so that it can use it (it is also possible to use something other than this, less confusing (EDITED, since you want to click an element)

  var clicked = this; jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function() { fadeItems(clicked); }); function fadeItems(el) { var slogan = jQuery(el).children('p').html(); 
+2
source

Use apply :

fadeItems.apply(this);

This way you can specify the context for calling the function (manually assigning this to fadeItems )

EDIT: as @KevinB noted, you will need the alias this in the parent function: var that = this; , and then pass that to fadeItems.apply(that); .

+2
source

Source: https://habr.com/ru/post/914237/


All Articles