meo
meo

Reputation: 31259

simple toggle problem

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?

Upvotes: 0

Views: 239

Answers (3)

user113716
user113716

Reputation: 322582

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.

Upvotes: 3

z33m
z33m

Reputation: 6053

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;    
    })
}

Upvotes: 1

David Fullerton
David Fullerton

Reputation: 3254

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) }
    );        
}

Upvotes: 3

Related Questions