Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.on() & toggle working together

Tags:

jquery

toggle

Quick question here guys, I cant seem to get this

$('#wrap').on('toggle', '#image', function(){
    <!-- Do stuff -->
  });

to be able to have a toggle inside it? Any ideas? I have tried googling but with no luck.

this is the code i am trying to get to work with .on, as currently it doesn't apply the changes to all of the element son the page, (that have #image and #brick)

$("#result_options").toggle(function() {
        var image_width = $('#image').width() / 2;
        var brick_width = $('#brick').width() / 2;
        $("#image").css("width",image_width);
        $("#image").css("padding","4px");
        $("#brick").css("width",brick_width);
    },function (){
        $("#image").css("width","300");
        $("#image").css("padding","8px");
        $("#brick").css("width","314");
        $(this).html("Smaller Results");
    });
});
like image 289
Harry Avatar asked Jun 02 '12 17:06

Harry


1 Answers

The problem you're facing is that there is no toggle event; toggle() is a jQuery method. To implement a toggle(), with on() I think you'd need to use a click event, and then an if statement to test whether something's been toggled on, or toggled-off/not-toggled

$('#wrap').on('click', '#image', function(){
    if (!$(this).attr('data-toggled') || $(this).attr('data-toggled') == 'off'){
        /* currently it's not been toggled, or it's been toggled to the 'off' state,
           so now toggle to the 'on' state: */
           $(this).attr('data-toggled','on');
           // and do something...
    }
    else if ($(this).attr('data-toggled') == 'on'){
        /* currently it has been toggled, and toggled to the 'on' state,
           so now turn off: */
           $(this).attr('data-toggled','off');
           // and do, or undo, something...
    }
});
like image 136
David Thomas Avatar answered Nov 15 '22 18:11

David Thomas