Using jQuery Live instead of jQuery Hover function

Let’s say we have a case where we need to create mouseover / mouseout functionality for a list which will be dynamically filled with data on client-side.

We can use jQuery hover function, which handles the mouseover and mouseout events with two functions.

See the following example:

<!DOCTYPE html>
<html lang="en">
<head id="Head1" runat="server">
    <title>jQuery Mouseover / Mouseout Demo</title>

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js"></script>
    <style type="text/css">
        .hover { color:Red; cursor:pointer;}
    </style>
    <script type="text/javascript">
        $(function () {
            $("li").hover(
              function () {
                  $(this).addClass("hover");
              },
              function () {
                  $(this).removeClass("hover");
              });
        });
    </script>
</head>
<body>
    <form id="form2" runat="server">
    <ul>
        <li>Data 1</li>
        <li>Data 2</li>
        <li>Data 3</li>
        <li>Data 4</li>
        <li>Data 5</li>
        <li>Data 6</li>
    </ul>
    </form>
</body>
</html>

Now, if you have situation where you want to add new data dynamically... Lets say you have a button to add new item in the list.

Add the following code right bellow the </ul> tag

<input type="text" id="txtItem" />
<input type="button" id="addNewItem" value="Add New Item" />

And add the following button click functionality:

//button add new item functionality
$("#addNewItem").click(function (event) {
    event.preventDefault();
    $("<li>" + $("#txtItem").val() + "</li>").appendTo("ul");
});

The mouse over effect won't work for the newly added items. Therefore, we need to use live or delegate function. These both do the same job. The main difference is that for some cases delegate is considered a bit faster, and can be used in chaining.

In our case, we can use both. I will use live function.

$("li").live("mouseover mouseout",
  function (event) {
      if (event.type == "mouseover") $(this).addClass("hover");
      else $(this).removeClass("hover");
  });

The complete code is:

<!DOCTYPE html>
<html lang="en">
<head id="Head1" runat="server">
    <title>jQuery Mouseover / Mouseout Demo</title>

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js"></script>
    <style type="text/css">
        .hover { color:Red; cursor:pointer;}
    </style>
    <script type="text/javascript">
        $(function () {
            $("li").live("mouseover mouseout",
              function (event) {
                  if (event.type == "mouseover") $(this).addClass("hover");
                  else $(this).removeClass("hover");
              });

            //button add new item functionality
            $("#addNewItem").click(function (event) {
                event.preventDefault();
                $("<li>" + $("#txtItem").val() + "</li>").appendTo("ul");
            });
        });
    </script>
</head>
<body>
    <form id="form2" runat="server">
    <ul>
        <li>Data 1</li>
        <li>Data 2</li>
        <li>Data 3</li>
        <li>Data 4</li>
        <li>Data 5</li>
        <li>Data 6</li>
    </ul>
    

    <input type="text" id="txtItem" />
    <input type="button" id="addNewItem" value="Add New Item" />
    </form>
</body>
</html>

So, basically when replacing hover with live, you see we use the mouseover and mouseout names for both events.

Check the working demo which is available HERE.

UPDATE (12.02.2011 01:05AM CET)


NOTE: As Mr. Steve Wellens noted in the comments, the jQuery LIVE function can be used to connect handler to any event for the given selector. In some cases I prefer using DELEGATE function, but lets leave it for another topic. So, in order not to make confusion, the blog shows one useful way to replace HOVER with LIVE for a situation where HOVER cannot satisfy our needs. So, you can add additional events to which you want the LIVE function to connect the handle. See the following example:

$(function () {
    $("li").live("mouseover mouseout click",
      function (event) {
          if (event.type == "mouseover") $(this).addClass("hover");
          else if (event.type == "mouseout") $(this).removeClass("hover");
          else $(this).toggleClass("clicked");
      });

Besides the mouseover and mouseout, I added click event also. Then I'm just checking the type. If you test this, also define .clicked { background-color:Yellow; } class in your CSS ;).

In this example I only show changing of colors and working with jQuery CSS-related classes. You can perform additional operations by writing your own JavaScript / jQuery code.


 

Hope this was useful blog for you.

Hope it’s helpful.

Hajan

Reference blog: http://codeasp.net/blogs/hajan/microsoft-net/1260/using-jquery-live-instead-of-jquery-hover-function

10 Comments

  • The use of the 'live' function isn't restricted to hover events (mouseover, mouseout). It can be used to dynamically connect a handler to ANY event.

    http://weblogs.asp.net/stevewellens/archive/2011/01/24/the-jquery-live-function.aspx

  • @SGWellens, definitely true. The blog example shows only one example of how to replace hover with live. However, as you said, live can be used to connect handler to any event. Actually in most of the cases I use live (and from jQuery 1.4.2 and up the delegate) for situations when I want to add handler to events for selectors that are created dynamically on client-side. I have some nice usage examples together with jQuery Templates. I might post some blogs on this...

    Thank you for your comment.

  • @Steve, I just updated the blog because I think it's good to mention that live can be used to connect handler to any event so that others won't get confused or misunderstand the usage of the .live();

    Thanks once again.

  • >> Thanks once again.

    No charge amigo! :)

  • Very good Hajan, I was not aware of this live function in jquery. Keep it up...

    -
    www.technobits.net

  • @Steve ;)

    @Aamir, you can also take a look at the jQuery Delegate function. Tnx.

  • You should use mouseenter() instead of mouseover in this case. mouseover triggers on every mousemove while you are still on the element, and can thus trigger a lot of times. mouseenter triggers only once when you enter the element which is a lot more efficient while it does job.

    Cheers,
    Wes

  • @webbes, that's definitely true. So we can replace mouseover with mouseenter and mouseout with mouseleave ;). However, still the main point of the blog is showing the usage of the jQuery live() :). Thank you for your contribution.

  • Coolies! A quick question here in regards to jquery.live(), would that be working just fine if I have a asp.net UpdatePanel control wrapped around those HTML elements which has any sort of jquery behaviors associated with, after the Ajax Postback has been fired for that particular UpdatePanel control?

    If yes, that's just fabulous!

  • @Eric, yes. That's another case where jQuery live function has good application in. For such scenarios, you can also see my other blog post http://weblogs.asp.net/hajan/archive/2010/10/07/make-them-to-love-each-other-asp-net-ajax-updatepanels-amp-javascript-jquery-functions.aspx. I have posted some workarounds without using jQuery live, but you can see in the comments there some users mentioned this. So, once again yes jQuery Live will do that perfectly ;).

Comments have been disabled for this content.