jQuery Tooltip in MVC3 Razor


  1. In this article we will see how to use jQuery Tooltip.
  2. Tooltips can be attached to any element. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip.
  3. Tooltips are also useful for form elements, to show some additional information in the context of each field.
  4. The default tooltip shown in different browser limits the number of characters to display, like IE7 shows only 572 characters as default tooltip. Using this jQuery tooltip we can display any number of characters.
  5. We have integrated this tooltip with MVC3 Razor application.

Following are the steps :

View :

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p title="Hello world">This is demo for jQuery Tooltip.</p>


<script type="text/javascript">
    $(function () {
        $("p").tooltip();
    });
</script>


In the above view, we have referenced the layout file. The Layout file has references of all script files needed to render jQuery tooltip. We have defined a paragraph element with title attribute. In the script section we have used tooltip method, when the paragraph element is hovered the jQuery tooltip is displayed. The tooltip function uses the title attribute of element selected to show content in the tooltip window.

Layout :



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.core.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.position.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.tooltip.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>

The above is the layout file. It has references of script files required to use jQuery tooltip. This layout is referenced in View where we want to use jQuery tooltip.

Demo :


Hover the text.


In the above demo, when you hover the paragraph element, its title attribute is used to show the content in the tooltip.

Thus following the above steps we can use jQuery tooltip and can fulfill our requirements.

0 comments:

Post a Comment