6

I created a little jquery script and I have a problem to use (this) in a custom 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);
    });
}

So the function runs when clicking on a list items and that goes wel but the values of (this) is empty

Somebody know how to fix this?

Thanks in advance!

3 Answers 3

2

.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);
    }    
});
Sign up to request clarification or add additional context in comments.

Comments

2

Because you must pass it to the function so that it can use it (also maybe use domething different from this, is less confusing (EDITED since you want the clicked item)

    var clicked = this;
    jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function()
    {
        fadeItems(clicked);
    });

function fadeItems(el)
{       
var slogan = jQuery(el).children('p').html();

1 Comment

this in that case is not the element he's looking for.
2

Use apply:

fadeItems.apply(this);

That way you can specify the context for the function call (manually assigning the value of this in fadeItems)

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

2 Comments

That works great in the else {}, but within the animate this refers to the html and body elements
Ah, good catch. Principle is the same, but you need to store the context in the parent scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.