That is because the event is getting registered from DOM. Register it dynamically, Then It works.
Remove onclick
attribute from markup.
var count = 0;
$('#title').click(saygoodbye);
function saygoodbye(){
alert("ok is outer");
$("#title").html("goodbye");
$("#title").click(function() {
alert("ok is inner");
$('#title').html("hello");
$('#title').off("click");
});
}
<script src="//code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<h1 id="title">hello</h1>
Read this SO thread to get an insight as to why to register events on the go (For your case).
jQuery.click() vs onClick
EDIT:
First, In order to unbind events which are triggered thru element's attribute we need to use
document.getElementById("title").onclick = null;
Secondly, jQuery's .off() function will only unbind handlers that were added by jQuery's .on()
Documentation at http://api.jquery.com/off/
- "The .off() method removes event handlers that were attached with
.on()
"
.click()
- is a shorthand methods of .on()
So saygoodbye() doesn't get away, Here is the debugging.
click title.(having title hello)
- call goodbyefunction alert 'outer';
- change html to 'goodbye' assign
- new anonymous handler to title (on click event).
click title (having title goodbye)
- call goodbyefunction
- alert 'outer';
- change html to 'goodbye' (yes it
changes again)
- assign another event anonymous handler to title (see
1 more handler attached)
- call anonymous handler 1
- alert 'inner'
- although at this stage (.off() function is specified. this will only
execute if all events are triggered);
- call anonymous handler 2
- alert 'inner '
.off()
function works here and kills extra added 2
handlers.
Hope this breakdown helps.