Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery call custom function on click

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 :)

like image 994
Ben_hawk Avatar asked Sep 26 '26 07:09

Ben_hawk


2 Answers

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");
like image 177
jantimon Avatar answered Sep 27 '26 21:09

jantimon


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);
});
like image 22
Niko Avatar answered Sep 27 '26 21:09

Niko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!