Wednesday, September 4, 2013

Hover over for a text hint box Using jQuery



First we create a div with id hintbox to hold text hint box
<div id="hintbox"></div>
Using  CSS to difine hintbox  border, background color, text color; using position: absolute so we can modify top and left later.
 #hintbox{
    display:none;
    position: absolute;
    font-size: 12 px;
    background-color: #161616;
    color: #fff;
    border: 1px solid red;
    padding: 8px;
    border-radius:5px;
  }       

 create a button and input text boxfor mouse over,  define hinttext to hold the text showing in hint text box
<button type="button" class="hover" hinttext="Click to submit">Submit</button>
<input type="text"  class="hover"  hinttext="Enter your name" />
jQuery code, using mousemove to show text box when mouse over, using mouseout to hid text box:
$(document).ready(function() {
 $('.hover').mousemove(function(e){
       var hovertext = $(this).attr('hinttext'); 
         $('#hintbox').text(hovertext).show();
    $('#hintbox').css('top',e.clientY+15).css('left',e.clientX+15);})
     .mouseout(function(){
    $('#hintbox').hide();
 });
});

Complet example:
<html>
<head>
<style>
 #hintbox{
    display:none;
    position: absolute;
    font-size: 12 px;
    background-color: #161616;
    color: #fff;
    border: 1px solid red;
    padding: 8px;
    border-radius:5px;
  }       
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
 $('.hover').mousemove(function(e){
       var hovertext = $(this).attr('hinttext'); 
         $('#hintbox').text(hovertext).show();
    $('#hintbox').css('top',e.clientY+15).css('left',e.clientX+15);})
     .mouseout(function(){
    $('#hintbox').hide();
 });
});
</script>
</head>
<body>
<h1>Hover over for a text hint box using jQuery</h1>
<div id="hintbox"></div>
<h2>Applied to a button</h2>
<button type="button" class="hover" hinttext="Click to submit">Submit</button>

<h2>Applied to a input field</h2>
<input type="text"  class="hover"  hinttext="Enter your name" />
</body>
</html>

No comments:

Post a Comment