Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Smarter Event Binding

$("p").live("click", function(){
      $(this).css("color", "red");
});

The reason this is smarter is because there are likely many p elements on the page. If there were, say, 10 of them, traditional click event binding would require 10 handlers. The live function only requires one, reducing memory needed by the browser. Then imagine compounding the issue by 100 (for example, a table with 1000 cells with hover events).

Additionally, using the live function does not require events to be re-bound when additional elements are added to the page (like via AJAX).

Reference URL

Comments

  1. Brian
    Permalink to comment#

    Just a heads up that .live() is now depreciated in jQuery 1.7 and up. Instead you need to use the .on() method instead.

  2. webster
    Permalink to comment#

    “live” is deprected, use “on” instead

  3. shikhar srivastava
    Permalink to comment#

    Hey people this live method is deprecated officially by jQuery.
    Now we use .on() method to replicate .live() functionality.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```