<!DOCTYPE html>
<html>
<head>
<title>View Image</title>
<link rel="stylesheet" href="script01.css">
<script src="script02.js"></script>
</head>
<body>
<h2 class="centered">Image Viewer</h2>
<form action="#">
<p>
<label>
Image URL:
<input class="imgURL" type="text" size="50">
</label>
</p>
<p>
<input type="submit" value="Submit">
<input type="reset">
</p>
</form>
<img src="images/spacer.gif"
alt="Your image here" id="chgImg">
</body>
</html>
window.onload = function() {
document.forms[0].onsubmit = validForm;
}
function validForm() {
var allGood = true;
// Create a list of all tags in the first form
var allTags = document.forms[0].getElementsByTagName("*");
// Run the validTag function on every tag
for (var i=0; i<allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return false;
function validTag(thisTag) {
var outClass = "";
// Split the classname on a space delimiter
var allClasses = thisTag.className.split(" ");
for (var j=0; j<allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
invalidLabel(thisTag.parentNode);
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "imgURL":
if (allGood && !setImgURL(thisTag.value)) {
classBack = "invalid ";
}
default:
classBack += thisClass;
}
return classBack;
}
function setImgURL(newURL) {
var re = /^(file|http):\/\/\S+\/\S+\.(gif|jpg|png)$/i;
if (re.test(newURL)) {
document.getElementById("chgImg").src = newURL;
return true;
}
return false;
}
function invalidLabel(parentTag) {
if (parentTag.nodeName == "LABEL") {
parentTag.className += " invalid";
}
}
}
}
body {
color: #000;
background-color: #FFF;
}
input.invalid {
background-color: #FF9;
border: 2px red inset;
}
label.invalid {
color: #F00;
font-weight: bold;
}
.centered {
text-align: center;
}
Image Viewer