The following code only displays the last .text upadate. It works as expected with alert(),
$(‘#jTest')
.bind(‘click’,function(event) {
alert(‘Hello!’);
})
.bind(‘click’,function(event) {
alert(‘Hello again!’);
})
.bind(‘click’,function(event) {
alert(‘Hello yet again!’);
});
How can I craft my attempt, to behave as the alert?
$('#jTest')
.bind('click',function(event){
$(this).text("1st Click").css("fontSize","2em");
})
.bind('click',function(event){
$(this).text("2nd Click").css("fontSize","4em");
})
.bind('click',function(event){
$(this).text("3rd Click").css("fontSize","6em");
});
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id = "jTest"><p>Test Data String</p></div>
</body>
</html>
If you bind event handlers to an element, then all of them are executed when the event occurs. You see the three alerts one after another, because
alertis blocking. I.e. JavaScript continuous executing after you clickok.Changing the text or CSS is not blocking, but it is changed three times. It is just so fast that you don’t see it.
If you want to change the text on alternate clicks (or execute different callbacks in general), you can use
.toggle[docs]:DEMO
This would cycle over the event handlers (you did not mention what you actually want to do).