Asked  7 Months ago    Answers:  5   Viewed   35 times

I am looking for a way to have two separate operations / functions / "blocks of code" run when something is clicked and then a totally different block when the same thing is clicked again. I put this together. I was wondering if there was a more efficient / elegant way. I know about jQuery .toggle() but it kind of sucks.

Working here: http://jsfiddle.net/reggi/FcvaD/1/

var count = 0;
$("#time").click(function() {
    count++;
    //even odd click detect 
    var isEven = function(someNumber) {
        return (someNumber % 2 === 0) ? true : false;
    };
    // on odd clicks do this
    if (isEven(count) === false) {
        $(this).animate({
            width: "260px"
        }, 1500);
    }
    // on even clicks do this
    else if (isEven(count) === true) {
        $(this).animate({
            width: "30px"
        }, 1500);
    }
});

 Answers

80

jQuery has two methods called .toggle(). The other one [docs] does exactly what you want for click events.

Note: It seems that at least since jQuery 1.7, this version of .toggle is deprecated, probably for exactly that reason, namely that two versions exist. Using .toggle to change the visibility of elements is just a more common usage. The method was removed in jQuery 1.9.

Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).


(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

DEMO

(Disclaimer: I don't say this is the best implementation! I bet it can be improved in terms of performance)

And then call it with:

$('#test').clickToggle(function() {   
    $(this).animate({
        width: "260px"
    }, 1500);
},
function() {
    $(this).animate({
        width: "30px"
    }, 1500);
});

Update 2:

In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. It can be found on GitHub.

Tuesday, June 1, 2021
 
Baba
answered 7 Months ago
23

It probably because when you bind those functions there are no results for $(".portlet-header .ui-icon-plusthick"). It doesn't find it. You may add this binding to $(".portlet-header .ui-icon-minusthick").click(function() { ... after adding "ui-icon-plusthick" class.

EDIT: Alternative solution could be:

$(".portlet-header .ui-icon-minusthick").toggle(function() {
        $(this).removeClass("ui-icon-minusthick");
        $(this).addClass("ui-icon-plusthick");
        $(this).parents(".portlet:first").find(".portlet-content").toggle();
    }, function() {
        $(this).removeClass("ui-icon-plusthick");
        $(this).addClass("ui-icon-minusthick");
        $(this).parents(".portlet:first").find(".portlet-content").toggle();
    });

So first click would be first function and second click would be second function.

Saturday, July 17, 2021
 
binoculars
answered 5 Months ago
61

You may also checkout the UI.Layout jQuery plugin. Here's a demo.

Sunday, August 8, 2021
 
Scott Chantry
answered 4 Months ago
74

A micro jQuery plugin:

jQuery.fn.clickToggle = function(a,b) {
  var ab = [b,a];
  return this.on("click", function(){ ab[this._tog^=1].call(this); });
};


// USE LIKE:

$("button").clickToggle(function() {   
     console.log("AAA");
}, function() {
     console.log("BBB");
}); // Chain here other jQuery methods to your selector

Taken from my answer here https://stackoverflow.com/a/21520499/383904


There's other ways to toggle a state / value:

LIVE DEMO

var editAdd = [editList, addList],  // store your function names into array
    c = 0;                          // toggle counter

function editList(){                // define function
   alert('EDIT');
}
function addList(){                 // define function
   alert('ADD');
}

$('#edit a').click(function(e){  
  e.preventDefault();
  editAdd[c++%2]();                 // toggle array index and use as function
                                    // % = Modulo operator
});

where instead of the modulo operator % you can use the
Bitwise XOR operator ^ like: [c^=1]


Using Array.reverse()
LIVE DEMO

var editAdd = [editList, addList];

function editList(){
   alert('EDIT');
}
function addList(){
   alert('ADD');
}

$('#edit a').click(function(e){  
  e.preventDefault();
  editAdd.reverse()[0]();
});

reverse will invert our array on every click, all we need to do is take the 0 indexed value [0] and run that function name [0]().

Sunday, August 15, 2021
 
aurelijusv
answered 4 Months ago
91

As I tried out and read through the link given by @konrad, I found that its a bug in Jquery UI - even in the latest version of it. The problem got solved as soon as I started using Jquery UI 1.9.2 version

here is the updated fiddle: http://jsfiddle.net/deveshz/YvmFf/2/

with same code:

var zindex = 10; 
$(".item").draggable({
    containment: "body",
    scroll: true,
    revert: function (event, ui) {
        $(this).css("border", "none");
        return !event;
   },
    start: function (event, ui) {
        $(this).css("z-index", zindex++);
        $(this).css("border", "2px solid #333");
    }
});

 $(".stack_items").droppable({
    hoverClass: "over",
    drop: function (event, ui) {
        $("<li class='item'></li>").html(ui.draggable.html()).appendTo(this);
        $(ui.draggable).remove();
    }
});

It uses Jquery version 1.9.2 from http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js

Wednesday, August 25, 2021
 
StampyCode
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share