Skip Navigation | Groups

This site uses cookies- for more information see the Cookie Policy | Continue

 

Overlaying Graphics with jQuery

HTML and JavaScript using jQuery


How to place an arrow between two points

If you hover the mouse herearrow an arrow appears pointing to Image-3  below.

This example works best when the font-size is fixed, and the user does not adjust it. Unfortunately, users cannot be stopped from adjusting font sizes to suit their own needs. For example, the user may need larger fonts to see the text, or to compensate for a very high resolution screen on a small Tablet PC. Changing the font size will change the position of the arrow's endpoints, and will also change the position of Image-3 - the arrow's top endpoint is fixed relative to the word "here", but not fixed relative to the page. In other words - the arrow will move as text is resized.

Ford Anglia - circa 1953
Image 1
Frog Eyed Sprite
Image 2
 
    Image that is swapped
Image 3

HTML

The first paragraph on this page contains the HTML for the arrow and the link that displays it. This is shown below:

<p>If you hover the mouse <span class="sp1">here
<img id="arrow" src="~/fp/articles/images/arrow1.gif" 
alt="arrow" /></span> an arrow appears pointing to 
Image-3&nbsp; below.</p>

<span class="sp1"> is a <span> that contains the arrow. Hovering over the word "here" within the <span> displays the arrow - moving away hides it. The <span> will obviously move with the text as the browser is resized, or as the text is resized, and the arrow, being within the <span>, will move with it. jQuery finds the 'class="sp1"' and "listens" for the hover (onmouseover and onmouseout) events, and shows/hides the arrow accordingly.

<img id="arrow" src="~/fp/articles/images/arrow1.gif" alt="arrow" /> is the arrow. CSS sets it's position to absolute, which means when the arrow is displayed it will display over the page content, rather than shift the page content out of its way.

CSS

.sp1 {
position: relative;
font-style: italic; 
border-bottom: 1px dashed blue; 
}
#arrow {
position: absolute;
z-index: 1;
left: 1em;
top: 1.2em;
width: 195px;
height: 20em;
visibility: hidden;
}

The above CSS sets the <span>  to position: relative, and sets the size and position and initial visibility (hidden) of the arrow. Using position: absolute enables the arrow to float over the page content.

Javascript

$('document').ready(function() {
$('#arrow').hide();
$('.sp1').hover(function() {
$('#arrow').toggle();
});
});

The above javascript, together with the jQuery library, is all that is needed to show and hide the arrow.

Also see the code comparison between the behaviours and jquery methods.