0

I am trying to expand a div on click, and on another click shrink it again. When this function is called, nothing happens.

jQuery Code:

$(".panel").toggle(function()
{
    $(this).click(function()
    {
        $(this).animate({width:'300px',height:'300px'}, 200);
    });
},
function()
{
    $(this).click(function()
    {
        $(this).animate({width:'152px',height:'152px'}, 200);
    });
});
Orbling
  • 20,413
  • 3
  • 53
  • 64
Legatro
  • 3,692
  • 4
  • 15
  • 21
  • 1
    possible duplicate of [Where has fn.toggle( handler(eventObject), handler(eventObject)...) gone?](http://stackoverflow.com/questions/14301935/where-has-fn-toggle-handlereventobject-handlereventobject-gone) – j08691 May 30 '13 at 17:40
  • What version of JQuery? Also, make a jsbin with some more code in it – JClaspill May 30 '13 at 17:41
  • If possible can you provide html code as well? – Edward May 30 '13 at 17:41
  • 1
    a solution is remove `$(this).click(function()`, but better read about toggle deprecation – Michael Aguilar May 30 '13 at 17:44
  • Why do you have `.click()` nested in the toggle? – Orbling May 30 '13 at 17:44
  • It's not a duplicate of that toggle deprecation, but it is relevant. – Orbling May 30 '13 at 17:44
  • 1
    @j08691 This isn't a duplicate really. This is wanting a means to an end, without specifying they are requiring the use of .toggle – JClaspill May 30 '13 at 17:44
  • @JClaspill - the question I linked to discusses how the use of the `toggle()` methods has been removed from jQuery and an alternate way to simulate the same functionality. – j08691 May 30 '13 at 18:18
  • @j08691 Yes, it is a valid link to provide as a reference for not using toggle in this instance. But this question isn't a duplicate, which is what you flagged it as. – JClaspill May 30 '13 at 18:22

2 Answers2

4

toggle() only hides and displays the div, and it does not take in two functions as parameters. http://api.jquery.com/toggle/

Here is my solution to this, although I am not sure if this is the best, hope someone would point out improvements.

var next_move = "expand";
$(document).ready(function (){
$(".panel").click(function()
{
    var css = {};
    if (next_move == "expand"){
        css = {
            width: '300px',
            height: '300px'
        };
        next_move = "shrink";
    } else {
        css = {
            width: '152px',
            height: '152px'
        };     
        next_move = "expand";
    }
    $(this).animate(css, 200);
});
});

http://jsfiddle.net/Vc49G/

Enjoy!

Edward
  • 1,914
  • 13
  • 26
1

click() is not neccesary inside toggle functions, try this:

$(".panel").toggle(
function()
{
    $(this).animate({width:'300px',height:'300px'}, 200);
},
function()
{
    $(this).animate({width:'152px',height:'152px'}, 200);
}
);

By the way, this method was deprecated in jquery 1.8

Michael Aguilar
  • 766
  • 8
  • 16