3

How would I correctly call the specialHouse function after the h1 was clicked, in way that would still allow $(this) to represent div.content. Currently the below does not work with the error "Uncaught TypeError: Object [object Object] has no method 'specialHouse'"

function specialHouse()
{
    $(this).slideDown(500, function(){
      $(this).delay(2000).slideUp();
    });
 };

$('div.content').hide();
$('h1').on('click', function(){
    $(this).next('div.content').specialHouse();
})

Thanks for any help :)

3 Answers 3

6

You have to tell jQuery about your new function:

jQuery.fn.specialHouse = function() {
   return this.slideDown(500, function(){
     $(this).delay(2000).slideUp();
   }
}

As we return this our function is chain able:

$("a").specialHouse().text("Hello World");
Sign up to request clarification or add additional context in comments.

3 Comments

why do we have to return 'this' in order for the function to be chain-able :S
This is how every chain-able jQuery plugin works. this is returned and the next function may use it again.
FWIW, I think the other answer is better. It works without modifying the OP's original function, and thus allows that function to continue to be used as a standalone event handler.
5

The way you've tried it works only for jQuery plugins. You can however invoke the function like this (the context this will be set as expected):

$('h1').on('click', function() {
    $(this).next('div.content').each(specialHouse);
});

1 Comment

good way to do it without converting that function into a plugin
1

Try :

$('div.content').hide();
$('h1').on('click', function(){
    specialHouse($(this).next('div.content'));
}) 

function specialHouse(elem){
  $(elem).slideDown(500, function(){
     $(this).delay(2000).slideUp();
   });
};

1 Comment

The OP specifically requested $(this) - not a parameter.

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.