?
Solved

How to create an element once only

Posted on 2011-05-13
15
Medium Priority
?
300 Views
Last Modified: 2012-06-27
The following code creates a floating tooltip when the form elements are hovered over (courtesy of another expert in this TA!).  Am I correct in thinking that a new <div> gets appended to the body every time a form item is hovered over?
If so, can the code be streamlined to only create a single <div> for the tooltip, which just gets repositioned and has new html content when other items are hovered over?  Or, can the element be removed when hovering out?  Not sure which is the best way...!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
        <style type="text/css">
                .tooltip{display:none; position: absolute; top: 0; left: 0; z-index: 3; background-color:#eeeeee; padding:5px; border:1px solid gray}
        </style>
        <script type="text/javascript">
		//<![CDATA[
			function CreateTooltip(elementId, tipText){
				var tipdiv = $('<div id="'+elementId+'_tipdiv" class="tooltip" />');
				$('body').append(tipdiv);
				tipdiv.html(tipText);
				
				$("#"+elementId).hover(function(){
					$("#"+elementId+"_tipdiv").fadeIn(100);
					$("*").mousemove(function (e) {
                    	tipdiv.css({ 
							'margin-left': e.pageX + 10, 
							'margin-top': e.pageY + 10, 
							'z-index': '999' 
						});
                     });
				},
				function () {
						tipdiv.fadeOut(100);
				});
			}

            $(document).ready(function () {
				 CreateTooltip('txt','Some text');
				 CreateTooltip('another','More Text');
				 CreateTooltip('last','Last item text');
			});   
                //]]>
        </script>
</head>
<body>
        <form action="#" method="post">
                <p><input type="text" id="txt" /></p>
                <p><input type="text" id="another" /></p>
                <p><input type="text" id="last" /></p>
        </form>
</body>
</html>

Open in new window

0
Comment
Question by:Rouchie
  • 7
  • 5
  • 3
15 Comments
 
LVL 13

Expert Comment

by:ansudhindra
ID: 35753421
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 35753500
Yes, for each element there is a tooltip, but you need those - you're referencing the id of the element when showing the tooltip. You could mess with the code to delete the tooltip every time the mouse leaves the element, but why ? Is that a problem ?
0
 
LVL 25

Author Comment

by:Rouchie
ID: 35753538
On some pages there will be a lot of form elements that require a tooltip.  I was trying to keep the code running as efficient as possible, so therefore wanted to either remove the tooltip <div>'s, or just have one that provided the tooltip for all form elements.
JQuery isn't my strong point unfortunately so I was hoping somebody could provide me with a solution based on my original code.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 35753556
I just wonder if adding
tipdiv.remove();
after line 27 (tipdiv.fadeOut(100);) would be enough...

hover has two functions - one fires when the mouse is over, the other when out.
0
 
LVL 27

Accepted Solution

by:
Lukasz Chmielewski earned 2000 total points
ID: 35753619
Maybe this will do (I think it is working):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
        <style type="text/css">
                .tooltip{display:none; position: absolute; top: 0; left: 0; z-index: 3; background-color:#eeeeee; padding:5px; border:1px solid gray}
        </style>
        <script type="text/javascript">
		//<![CDATA[

            $(document).ready(function () {
            
                $('input[type=text]').hover(
                function(){
                    var thisid = $(this).attr('id');
                    var thisval = $(this).attr('alt');
                    var tipdiv = $('<div id="'+thisid+'_tipdiv" class="tooltip" />');
                    $('body').append(tipdiv);
                    tipdiv.html(thisval);
					$("#"+thisid+"_tipdiv").fadeIn(100);
					$("*").mousemove(function (e) {
                    	tipdiv.css({ 
							'margin-left': e.pageX + 10, 
							'margin-top': e.pageY + 10, 
							'z-index': '999' 
						});
                     });                    
                },
                function(){
                //alert("ok");
                        var thisid = $(this).attr('id');
                        var thisval = $(this).attr('alt');
                        var tipdiv = $('#'+thisid+'_tipdiv');                
						tipdiv.fadeOut(100);
						tipdiv.remove();                
                });
            
			});   
                //]]>
        </script>
</head>
<body>
        <form action="#" method="post">
                <p><input type="text" id="txt" alt="Some text" /></p>
                <p><input type="text" id="another" alt="More text" /></p>
                <p><input type="text" id="last" alt="Last item text" /></p>
        </form>
</body>
</html>

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 35753625
I have added alt attribute to every text field as a tooltip text
0
 
LVL 27

Assisted Solution

by:Lukasz Chmielewski
Lukasz Chmielewski earned 2000 total points
ID: 35753637
One last correction - to delete the tooltip after it fades out.
Change the line 35-36 of the above snippet to this

tipdiv.fadeOut(100,function(){
   tipdiv.remove();
});
0
 
LVL 13

Expert Comment

by:ansudhindra
ID: 35753732
Hello,

this code is working...
Just u need to add title attribute to the elements you need tool tip. attribute value will be shown in the tooltip.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
        <style type="text/css">
                .tooltip{display:none; position: absolute; top: 0; left: 0; z-index: 3; background-color:#eeeeee; padding:5px; border:1px solid gray}
        </style>
        <script type="text/javascript">
                //<![CDATA[

            $(document).ready(function() {
            	
                $("body").append("<div id='ToolTipDiv' class='tooltip'></div>");
                $("[title]").each(function() {
                  $(this).hover(function(e) {
                    $(this).mousemove(function(e) {
                      
                      $("#ToolTipDiv").css({ 
                          'margin-left': e.pageX + 10, 
                          'margin-top': e.pageY + 10, 
                          'z-index': '999',
                          'display':'Block'
                  });
                    });
                    $("#ToolTipDiv")
                      .html($(this).attr('title'))
                      .stop(true,true)
                      .fadeIn("fast");
                    $("#ToolTipDiv").css({ 'display':'none' });
                  }, function() {
                    $("#ToolTipDiv")
                      .stop(true,true)
                      .fadeOut("fast")
                      .css({ 'display':'none' });
                    $(this).attr('ctitle', $("#ToolTipDiv").html());
                  });
                });
            	});
            
            
            
                //]]>
        </script>
</head>
<body>
        <form action="#" method="post">
                <p><input type="text" id="txt" title="First" /></p>
                <p><input type="text" id="another"  title="Second" /></p>
                <p><input type="text" id="last"  title="Third"/></p>
                <a href="#" title="Some text">some link</a>
                <p><input type="text" id="last2" title="My tool tip 1" /></p>
                <p><input type="text" id="last3" title="My tool tip 2" /></p>
                
        </form>
</body>
</html>

Open in new window

0
 
LVL 25

Author Comment

by:Rouchie
ID: 35753790
Thanks for your suggestions.  I had seen the approaches whereby ALT and TITLE are used to contain the tips.  The problem is that ALT is not a valid property for most items, and I use TITLE elsewhere on my pages for elements that should not have a tool tip.  Therefore, its important that I create these tooltips via a function call!  Sorry about that...!
0
 
LVL 25

Author Comment

by:Rouchie
ID: 35753795
Just to clarify, where I mention function call, I mean in this manner...

 $(document).ready(function () {
       CreateTooltip('txt','Some text');
       CreateTooltip('another','More Text');
       CreateTooltip('last','Last item text');
});  
0
 
LVL 13

Expert Comment

by:ansudhindra
ID: 35753840
You can change the attribute to anything you need..

may be link change the "title" to "customTitle"... and in javascript code update the title to customTitle at lines 15, 27 and 36.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 35753862
Sorry that's not possible because I'm writing strict xhtml!
0
 
LVL 27

Assisted Solution

by:Lukasz Chmielewski
Lukasz Chmielewski earned 2000 total points
ID: 35753958
This is almost impossible.
1. creating manually every tooltip with entering the text and textfield id
2. deleting it on mouseout would lead to lack of the action that creates it
3. you could not add the tooltip on mouseover, because you do it manually

What I'm saying is that deleting the tooltip would lead to more operations in fact that creating it once and leaving it on page. They are not visible and dynamic. This collides with nothing on page.
0
 
LVL 25

Author Comment

by:Rouchie
ID: 35754819
Okay thanks for that clarification.  I've adjusted the logic slightly, so that the tip <div> is created prior to the wiring up of events, and is also not removed after use but just hidden.  This code doesn't actually work, although there are no errors so I don't understand why, but is my approach a possibility (fixable)?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>Test</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
	<style type="text/css">
		.tooltip { display: none; position: absolute; top: 0; left: 0; background-color: #eeeeee; padding: 5px; border: 1px solid gray; }
	</style>
	<script type="text/javascript">
		//<![CDATA[
		function CreateTooltip(elementId, tipText) {
			var tipdiv = $('#tipdiv');
			tipdiv.hover(function () {
				tipdiv.html(tipText);
				tipdiv.fadeIn(100);
				$("*").mousemove(function (e) {
					tipdiv.css({
						'margin-left': e.pageX + 10 + 'px',
						'margin-top': e.pageY + 10 + 'px',
						'z-index': '999'
					});
				});
			},
				function () {
					tipdiv.fadeOut(100);
				});
		}

		$(document).ready(function () {
			var tipdiv = $('<div id="tipdiv" class="tooltip" />');
			$('body').append(tipdiv);
			CreateTooltip('txt', 'Some text');
			CreateTooltip('another', 'More Text');
			CreateTooltip('last', 'Last item text');
		});   
        //]]>
	</script>
</head>
<body>
<form action="#" method="post">
<p><input type="text" id="txt" /></p>
<p><input type="text" id="another" /></p>
<p><input type="text" id="last" /></p>
</form>
</body>
</html>

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 35756302
This does not do anything because the class tooltip makes it display: none - invisible. So hovering over it does in fact, nothing.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month13 days, 8 hours left to enroll

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question