Liam
Liam

Reputation: 9855

Use function to toggle div with jQuery

Im trying to write a function that when called toggles my 'p' tag.

I know I could use

$(this).click(function(){
    // Run my function here
});

But i want it as a function so it can be called and I can use it in multiple projects.

Can anybody see where im going wrong with this?

(function(toggle){
    $(this).on("click", function(){
        $(this).parent().find('p').slideToggle();
    });
})

Here the example code: http://jsfiddle.net/UBaSq/

Upvotes: 0

Views: 59

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

jQuery(function($){
    $('a').on("click", function(){
        $(this).parent().find('p').slideToggle();
    });
});

Demo: Fiddle

Upvotes: 1

mishik
mishik

Reputation: 10003

toggler = function() {
  $(this).parent().find("p").slideToggle();
}

// someElement will be passed as "this" to toggler
$("someElement").on("click", toggler); 

// Call toggler right away
toggler.apply($("someElement"));

Upvotes: 3

Related Questions