0

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/

1
  • you have not added any selectors for the click handler Commented Jul 8, 2013 at 10:12

2 Answers 2

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

2 Comments

Thanks @Mishik, Can I ask, what does the .apply do?
functionX.apply(obj, [arg1, arg2, ...]) == call functionX with arguments arg1, arg2,... and set this to obj. Similar: functionX.call(obj, arg1, arg2,...) == same as apply, but you need to list the arguments instead of supplying them via array.
1

Try

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

Demo: Fiddle

Comments

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.