-1

Since .live() has been deprecated, i'm using .on() instead of .live(), but it doesn't work properly, bear me if i am wrong, thanks in advance.

Below is a simple testing html, my expect behavior is that event fire only when i click the button, but it turns out event fires wherever i click.

<html lang="en">
<head>
  <title>demo</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="wrapper">
    <p>Hello World!</p>
    <p>Hello World!</p>
    <p>Hello World!</p>
    <p>Hello World!</p>
    <button id="btn">Click</button>
    <p>Hello World!</p>
    <p>Hello World!</p>
    <p>Hello World!</p>
    <p>Hello World!</p>
    <p>Hello World!</p>
</div>
<script>

$(document).on("click", $("#btn"), function(){ 

    document.title += "fire!";

});

</script>

</body>
</html>
gozizibj
  • 285
  • 1
  • 5
  • 23

2 Answers2

4

The second parameter to on() function should be the selector not the jQuery object.

$(document).on("click", "#btn", function(){ 
    document.title += "fire!";
});
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
0

FIDDLE

Use this as your script

$(function(){
   $('#btn').on('click', function(){
      alert('You clicked a button.');
   });
});
reggaemahn
  • 6,272
  • 6
  • 34
  • 59