First page Back Continue Last page Image

Previewing Links with AJAX

window.addEventListener("load",initAll,false);

var xhr = false;

var xPos, yPos;

function initAll() {

var allLinks = document.getElementsByTagName("a");

for (var i=0; i< allLinks.length; i++) {

allLinks[i].addEventListener("mouseover",getPreview,false);

}

}

function getPreview(evt) {

if (evt) {

var url = evt.target;

}

else {

evt = window.event;

var url = evt.srcElement;

}

xPos = parseInt(evt.clientX);

yPos = parseInt(evt.clientY);

if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest();

}

else {

if (window.ActiveXObject) {

try {

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

catch (e) {

}

}

}

if (xhr) {

xhr.addEventListener("readystatechange",showContents,false);

xhr.open("GET", url, true);

xhr.send(null);

}

else {

alert("Sorry, but I couldn't create an XMLHttpRequest");

}

}

function showContents() {

var prevWin = document.getElementById("previewWin");

if (xhr.readyState == 4) {

if (xhr.status == 200) {

prevWin.innerHTML = xhr.responseText;

}

else {

prevWin.innerHTML = "There was a problem with the request " + xhr.status;

}

prevWin.style.top = yPos+2 + "px";

prevWin.style.left = xPos+2 + "px";

prevWin.style.visibility = "visible";

prevWin.addEventListener("mouseout", function() {prevWin.style.visibility = "hidden";}, false);

}

}

<!DOCTYPE html>

<html>

<head>

<title>Previewing Links</title>

<link rel="stylesheet" href="script05.css">

<script src="script05.js"></script>

</head>

<body>

<h2>A Gentle Introduction to JavaScript</h2>

<ul>

<li><a href="jsintro/2000-08.html">August column</a></li>

<li><a href="jsintro/2000-09.html">September column</a></li>

<li><a href="jsintro/2000-10.html">October column</a></li>

<li><a href="jsintro/2000-11.html">November column</a></li>

</ul>

<div id="previewWin"> </div>

</body>

</html>

#previewWin {

background-color: #FF9;

width: 400px;

height: 100px;

font: .8em arial, helvetica, sans-serif;

padding: 5px;

position: absolute;

visibility: hidden;

top: 10px;

left: 10px;

border: 1px #CC0 solid;

clip: auto;

overflow: hidden;

}

#previewWin h1, #previewWin h2 {

font-size: 1.0em;

}

Here is the code but let's see what is happening first