tags:

views:

70

answers:

3

I'm just programming a little function that toggles a content by fading it in and out.

this.advancedSearch = function(fieldset, triggerBtn){
    fieldset.hide()
    triggerBtn.click(function(){
        fieldset.toggle(function(){ $(this).stop(false, true).fadeIn(300) }, function(){ $(this).stop(false, true).fadeOut(300) });
        return false;
    })
}

if just I use toggle() it works, but when i insert the two functions nothing happens and no error is thrown. Is there something i have done wrong?

+3  A: 

I assume that you intend the triggerBtn to fire the toggle event on fieldset.

If so, try this:

this.advancedSearch = function(fieldset, triggerBtn){
    fieldset.hide();
    triggerBtn.click(function(){
        fieldset.click();
    });
    fieldset.toggle(function(){ $(this).stop(false, true).fadeIn(300) }, 
                    function(){ $(this).stop(false, true).fadeOut(300) })
}

The way you had it, every time you clicked on triggerBtn, you were assigning the toggle event handler to the fieldset.


EDIT:

Alternatively, if you don't need the click (toggle) event on fieldset at all, then David's answer would work.

patrick dw
cool thanks it worked, why is it working when i just write .toggle() ?
meo
`toggle()` has different functionality depending on the parameters passed in. http://api.jquery.com/toggle/
patrick dw
+3  A: 

You want the toggle event to be attached to the object being clicked:

this.advancedSearch = function(fieldset, triggerBtn) {
    fieldset.hide()
    triggerBtn.toggle(
        function(){ fieldset.stop(false, true).fadeIn(300) }, 
        function(){ fieldset.stop(false, true).fadeOut(300) }
    );        
}
David Fullerton
+1  A: 

toggle function binds a click event on the element that toggles the element automatically.. so calling toggle inside your button click callback doesnt toggle the element, it simply binds an event. Its much simpler to implement this by hand rather than using toggle.

this.advancedSearch = function(fieldset, triggerBtn){
    fieldset.hide()
    triggerBtn.click(function(){
        if(fieldset.hasClass('toggle-on')) {
            fieldset
                .removeClass('toggle-on')
                .stop(false, true).fadeOut(300);
        }
        else {
            fieldset
                .addClass('toggle-on')
                .stop(false, true).fadeIn(300);
        }
        return false;    
    })
}
z33m
oh i did not know it bindes a click event! thanks but just toggle is much faster to write and use, when you know how :P
meo