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
DEMO
.one() documentation.
I am very late to answer but i think it's shortest code and might help.
function handler1() {
alert('First handler: ' + $(this).text());
$(this).one("click", handler2);
}
function handler2() {
alert('Second handler: ' + $(this).text());
$(this).one("click", handler1);
}
$("div").one("click", handler1);
DEMO With Op's Code
function handler1() {
$(this).animate({
width: "260px"
}, 1500);
$(this).one("click", handler2);
}
function handler2() {
$(this).animate({
width: "30px"
}, 1500);
$(this).one("click", handler1);
}
$("#time").one("click", handler1);
modifying the first answer you are able to switch between n functions :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus.com®">
<!-- <script src="../js/jquery.js"></script> -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<title>my stupid example</title>
</head>
<body>
<nav>
<div>b<sub>1</sub></div>
<div>b<sub>2</sub></div>
<div>b<sub>3</sub></div>
<!-- .......... -->
<div>b<sub>n</sub></div>
</nav>
<script type="text/javascript">
<!--
$(document).ready(function() {
(function($) {
$.fn.clickToggle = function() {
var ta=arguments;
this.data('toggleclicked', 0);
this.click(function() {
id= $(this).index();console.log( id );
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(ta[id], this)();
data.toggleclicked = id
});
return this;
};
}(jQuery));
$('nav div').clickToggle(
function() {alert('First handler');},
function() {alert('Second handler');},
function() {alert('Third handler');}
//...........how manny parameters you want.....
,function() {alert('the `n handler');}
);
});
//-->
</script>
</body>
</html>
I would do something like this for the code you showed, if all you need to do is toggle a value :
var oddClick = true;
$("#time").click(function() {
$(this).animate({
width: oddClick ? 260 : 30
},1500);
oddClick = !oddClick;
});
I used this to create a toggle effect between two functions.
var x = false;
$(element).on('click', function(){
if (!x){
//function
x = true;
}
else {
//function
x = false;
}
});