user253530
user253530

Reputation: 2591

Jquery SlideToggle needs to be clicked 2 times

I am using slideToggle to show some data in a div. Here's my code:

$('a.more').click(function(event){
            event.preventDefault();            
            var id = $(this).attr('cid');
            $.post('<?php echo $this->baseUrl('/teacher/class-members');?>',
            {cid: id},
            function(data) {                              
                $("div[cid='" + id + "']").slideToggle(500, function(){
                    $(this).html(data);
                });
            })
        });

The problem is that I need to click 2 times for the slide to activate and show the data. Why is this happening? It only needs to do this one time per link. So when I'm first viewing a page and I click on a link with class "more" I need to click 2 times (the $.post is executed 2 times :-/ ) for the toggle to work. After that It will work as it should, 1 click toggle down, 1 click toggle up.

Upvotes: 1

Views: 2210

Answers (2)

user253530
user253530

Reputation: 2591

$('a.more').click(function(event){
            event.preventDefault();            
            var id = $(this).attr('cid');
            $.post('<?php echo $this->baseUrl('/teacher/class-members');?>',
            {cid: id},
            function(data) {                              
                $("div[cid='" + id + "']").html(data).slideToggle(500);
            })
        });

Works nicely like this, no jumpy feeling.

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

What is the initial css state of div[cid=, if it is set to display block it will hide the div and than assign the html in the callback.

If you set the div to display:none it should work the first time however it will be jumpy as it only will set the html on the callback of slideToggle.

If you want to slide up on each click and load the data try this out:

$('a.more').click(function (event) {
    event.preventDefault();
    var id = $(this).attr('cid');
    var $div = $("div[cid='" + id + "']").slideUp(function(){$(this).empty();});
    $.post('<?php echo $this->baseUrl(' / teacher / class - members ');?>', {
        cid: id
    }, function (data) {
        $div.html(data).slideDown(500);
    })
});

Example on jsfiddle.

Upvotes: 2

Related Questions