Why does the first block using an anonymous function work differently from the second using a named function? The first block changes between "Hello" and "Goodbye" but the second doesn't.
1st — Using anonymous function:
function sayGoodbye() {
$("#title").html("Goodbye");
$("#title").click(function () {
$("#title").html("Hello");
$("#title").off("click");
});
};
2nd — Using named function:
function sayGoodbye() {
console.log("goodbye");
$("#title").html("Goodbye");
$("#title").click(sayHello());
};
function sayHello() {
console.log("hello");
$("#title").html("Hello");
$("#title").off("click");
}
HTML:
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1 id="title" onclick="sayGoodbye();"> Hello </h1>
</body>