Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change jQuery toggle() status

Using toogle to show/hide the div, I've got a problem that when I hide my div with anothor function, I have to click twice on the button to perform correct action.

Is there any way change the toggle switch like I clicked the button?

$('#add_task').toggle(function() { 
    if ($("#new_task_status").attr("value")==0) { 
        $("#new_task").slideDown();
        $("#new_task_status").attr("value", "1");
    }
}, function() {
    if ($("#new_task_status").attr("value")==1) { 
        $("#new_task").slideUp();
        $("#new_task_status").attr("value", "0");
    }
});


$('nav').click(function() { 
    if ($("#new_task_status").attr("value")==1) { 
        $("#new_task_status").attr("value", "0");
        $("#new_task").slideUp();
    }
});
like image 419
Zier Gofren Schlanum Avatar asked Nov 05 '22 12:11

Zier Gofren Schlanum


2 Answers

You could change your .toggle() so it doesn't matter, like this:

$('#add_task').click(function() { 
  $("#new_task").slideToggle(function() {
    $("#new_task_status").val($(this).is(':visible') ? 1 : 0);
  });
});

This does a slideToggle() instead, so the current state doesn't matter...when it finishes sliding, if it's shown (you opened it) you get a 1 in the input, otherwise you get a 0. Also, use .val() for input setting, much easier and more universal (I'm assuming it's an input here since that's most likely).

like image 135
Nick Craver Avatar answered Nov 12 '22 15:11

Nick Craver


No, you would have to implement your own alternative to the toggle() function, which checks the current state of the element.

like image 41
Sjoerd Avatar answered Nov 12 '22 14:11

Sjoerd