This document provides an overview of using JavaScript to add dynamic content and interactivity to web pages. It discusses generating HTML dynamically using document.write(), monitoring user events using event handlers like onclick, the basic syntax of JavaScript including dynamic typing, functions, objects and classes. It then gives examples of applications like determining browser window size, modifying images dynamically, and highlighting images as the mouse moves over them. The document is intended to teach core JavaScript programming concepts.
A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
In Angular , events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing.
Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding and they differ in the way the data is flowing.
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2015.
http://www.ivanomalavolta.com
A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
In Angular , events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing.
Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding and they differ in the way the data is flowing.
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2015.
http://www.ivanomalavolta.com
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
Slides from GeoDjango talk given by Eric Palakovich Carr. Last given in Washington, D.C. for django-district meetup on July 27th, 2011.
http://www.meetup.com/django-district/events/16015696/
Source code hosted on github:
https://github.com/bigsassy/geodjango_talk
jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects.
Basic Tutorial of React for ProgrammersDavid Rodenas
This is the support of a course to teach React programming for Java and C# programmers. It covers from its origins in Facebook til separation of presentational and container components. What is JSX, rules, state, props, refactoring, conditionals, repeats, forms, synchronizing values, composition, and so on.
Debugging in JavaScript
It is common to have errors while writing codes and the errors can be due to syntax or logical. These errors create a lot of ambiguity in the logic and understanding of both users and programmers. There can also be errors in the code which can remain invisible to the programmer’s eye and can create havoc. To identify these errors we need Debuggers that can go through the entire code or program, identify the errors and also fix them.
-Debugger
The debugger keyword is used in the code to force stop the execution of the code at a breaking point and calls the debugging function. The debugger function is executed if any debugging is needed at all else no action is performed.
The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser.
BOM provides you with window object, for example, to show the width and height of the window. It also includes the window.screen object to show the width and height of the screen.
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
2016 is going to be the year of Virtual DOM. React.js one of the most popular implementation of Virtual DOM. But this time we won't focus on React.js. We will be focusing on what is the concept of Virtual DOM, what's the benefits, and how to use it without React.js. All of those concepts will help you understand this newest DOM manipulation technique and better work with any Virtual DOM implementations such React.js.
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
Slides from GeoDjango talk given by Eric Palakovich Carr. Last given in Washington, D.C. for django-district meetup on July 27th, 2011.
http://www.meetup.com/django-district/events/16015696/
Source code hosted on github:
https://github.com/bigsassy/geodjango_talk
jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects.
Basic Tutorial of React for ProgrammersDavid Rodenas
This is the support of a course to teach React programming for Java and C# programmers. It covers from its origins in Facebook til separation of presentational and container components. What is JSX, rules, state, props, refactoring, conditionals, repeats, forms, synchronizing values, composition, and so on.
Debugging in JavaScript
It is common to have errors while writing codes and the errors can be due to syntax or logical. These errors create a lot of ambiguity in the logic and understanding of both users and programmers. There can also be errors in the code which can remain invisible to the programmer’s eye and can create havoc. To identify these errors we need Debuggers that can go through the entire code or program, identify the errors and also fix them.
-Debugger
The debugger keyword is used in the code to force stop the execution of the code at a breaking point and calls the debugging function. The debugger function is executed if any debugging is needed at all else no action is performed.
The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser.
BOM provides you with window object, for example, to show the width and height of the window. It also includes the window.screen object to show the width and height of the screen.
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
2016 is going to be the year of Virtual DOM. React.js one of the most popular implementation of Virtual DOM. But this time we won't focus on React.js. We will be focusing on what is the concept of Virtual DOM, what's the benefits, and how to use it without React.js. All of those concepts will help you understand this newest DOM manipulation technique and better work with any Virtual DOM implementations such React.js.
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Session highlighting and demonstrating approaches to common challenges in modern portlet development. Topics include AJAX in JSR-168 and JSR-286 portlets, CSS and Javascript toolkits, security, and optimization of front-end resources. This session was presented at the Jasig Spring 2010 conference in San Diego, CA by Jennifer Bourey.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
Downloading jQuery file from jQuery website.
Referring to jQuery file through Content Delivery Networks.
Google CDN
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js>
</script>
Microsoft CDN
<script src=“http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js”>
</script>
Overview of The Scala Based Lift Web FrameworkIndicThreads
All of us having experience with other web frameworks such as Struts,Tapestry, Rails, etc would ask “Why another framework? Does Lift really solve problems any differently or more effectively than the ones we’ve used before? The Lift Web Framework provides an advanced set of tools for quickly and easily building real-time, multi-users, interactive web applications. Lift has a unique advantage that no other web framework currently shares: the Scala programming language. Scala is a relatively new language developed by Martin Odersky and his group at EPFL Switzerland. Scala is a hybrid Object Oriented and Functional language that runs at native speeds on the JVM and fully interoperates with Java code. Lift is a hybrid web framework built on Scala. Lift derives its features and idioms from the best of existing web frameworks as well as the functional and OO features in Scala. It compiles to Java bytecode and runs on the JVM, which means that we can leverage the vast ecosystem of Java libraries just as we would with any other java web framework. This presentation details the advantages of this Scala based Web framework over all the existing frameworks that we have used uptil now and shows a small sample application built with Lift. We will create a basic application with a model that maps to RDBMS, web pages that correspond to back end logic and bind dynamically created content to elements on the webpage.
JavaScript front end performance optimizationsChris Love
No one wants a slow loading, slow reacting application. As page weight has increased so has the dependency on JavaScript to drive rich user experiences. Today many pages load over 2MBs of JavaScript, but is this healthy? Do your scripts and dependencies perform well? In this session we will review common JavaScript performance bottlenecks, how to detect them and how to eliminate them.
This session will review common bad coding syntax, architecture and how to replace them with better alternatives. You will also be exposed to caching, code organization, build and deployment best practices that produce the best user experiences. Finally, you will see how to use the navigation timing and performance timing APIs to fine tune your applications to produce a fast, lean application your customers will love.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
2. JavaScript2 www.corewebprogramming.com
Agenda
• Generating HTML Dynamically
• Monitoring User Events
• Basic JavaScript Syntax
• Applications
– Using JavaScript to customize Web pages
– Using JavaScript to make pages more dynamic
– Using JavaScript to validate CGI forms
– Using JavaScript to manipulate HTTP cookies
– Using JavaScript to interact with and control frames
– Controlling applets and calling Java from JavaScript
– Accessing JavaScript from Java
3. JavaScript3 www.corewebprogramming.com
Generating HTML Dynamically
• Idea
– Script is interpreted as page is loaded, and uses
document.write or document.writeln to insert
HTML at the location the script occurs
• Template
...
<BODY>
Regular HTML
<SCRIPT TYPE="text/javascript">
<!--
Build HTML Here
// -->
</SCRIPT>
More Regular HTML
</BODY>
4. JavaScript4 www.corewebprogramming.com
A Simple Script
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>First JavaScript Page</TITLE>
</HEAD>
<BODY>
<H1>First JavaScript Page</H1>
<SCRIPT TYPE="text/javascript">
<!--
document.write("<HR>");
document.write("Hello World Wide Web");
document.write("<HR>");
// -->
</SCRIPT>
</BODY>
</HTML>
6. JavaScript6 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Example
<HTML>
<HEAD>
<TITLE>Extracting Document Info with JavaScript</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>Extracting Document Info with JavaScript</H1>
<HR>
<SCRIPT TYPE="text/javascript">
<!--
function referringPage() {
if (document.referrer.length == 0) {
return("<I>none</I>");
} else {
return(document.referrer);
}
}
7. JavaScript7 www.corewebprogramming.com
Extracting Document Info with
JavaScript, Example, cont.
...
document.writeln
("Document Info:n" +
"<UL>n" +
" <LI><B>URL:</B> " + document.location + "n" +
" <LI><B>Modification Date:</B> " + "n" +
document.lastModified + "n" +
" <LI><B>Title:</B> " + document.title + "n" +
" <LI><B>Referring page:</B> " + referringPage() + "n" +
"</UL>");
document.writeln
("Browser Info:" + "n" +
"<UL>" + "n" +
" <LI><B>Name:</B> " + navigator.appName + "n" +
" <LI><B>Version:</B> " + navigator.appVersion + "n" +
"</UL>");
// -->
</SCRIPT>
<HR>
</BODY>
</HTML>
15. JavaScript15 www.corewebprogramming.com
JavaScript Syntax: Dynamic
Typing
• Idea
– Like Lisp, values are typed, not variables
– A value is only checked for proper type when it is
operated upon
• Example
var x = 5; // int
x = 5.5; // float
x = "five point five"; // String
16. JavaScript16 www.corewebprogramming.com
JavaScript Syntax: Function
Declarations
1. Declaration Syntax
– Functions are declared using the function reserved word
– The return value is not declared, nor are the types of the
arguments
– Examples:
function square(x) {
return(x * x);
}
function factorial(n) {
if (n <= 0) {
return(1);
} else {
return(n * factorial(n - 1));
}
}
17. JavaScript17 www.corewebprogramming.com
JavaScript Syntax: Function
Declarations, cont.
2. First Class Functions
• Functions can be passed and assigned to variables
• Example
var fun = Math.sin;
alert("sin(pi/2)=" + fun(Math.PI/2));
18. JavaScript18 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes
1. Fields Can Be Added On-the-Fly
– Adding a new property (field) is a simple matter of
assigning a value to one
– If the field doesn’t already exist when you try to assign
to it, JavaScript will create it automatically.
– For instance:
var test = new Object();
test.field1 = "Value 1"; // Create field1 property
test.field2 = 7; // Create field2 property
19. JavaScript19 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.
2. You Can Use Literal Notation
– You can create objects using a shorthand “literal”
notation of the form
{ field1:val1, field2:val2, ... , fieldN:valN }
– For example, the following gives equivalent values to
object1 and object2
var object1 = new Object();
object1.x = 3;
object1.y = 4;
object1.z = 5;
object2 = { x:3, y:4, z:5 };
20. JavaScript20 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.
3. The "for/in" Statement Iterates Over
Properties
• JavaScript, unlike Java or C++, has a construct that lets
you easily retrieve all of the fields of an object
• The basic format is as follows:
for(fieldName in object) {
doSomethingWith(fieldName);
}
• Also, given a field name, you can access the field via
object["field"] as well as via object.field
21. JavaScript21 www.corewebprogramming.com
Field Iteration, Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>For/In Loops</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function makeObjectTable(name, object) {
document.writeln("<H2>" + name + "</H2>");
document.writeln("<TABLE BORDER=1>n" +
" <TR><TH>Field<TH>Value");
for(field in object) {
document.writeln (" <TR><TD>" + field +
"<TD>" + object[field]);
}
document.writeln("</TABLE>");
}
// -->
</SCRIPT>
22. JavaScript22 www.corewebprogramming.com
Field Iteration, Example
...
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>For/In Loops</H1>
<SCRIPT TYPE="text/javascript">
<!--
var test = new Object();
test.field1 = "Field One";
test.field2 = "Field Two";
test.field3 = "Field Three";
makeObjectTable("test", test);
// -->
</SCRIPT>
</BODY>
</HTML>
24. JavaScript24 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.
4. A “Constructor” is Just a Function that
Assigns to “this”
• JavaScript does not have an exact equivalent to Java’s
class definition
• The closest you get is when you define a function that
assigns values to properties in the this reference
• Calling this function using new binds this to a new
Object
• For example, following is a simple constructor for a
Ship class
function Ship(x, y, speed, direction) {
this.x = x;
this.y = y;
this.speed = speed;
this.direction = direction;
}
26. JavaScript26 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.
5. Methods Are Function-Valued Properties
• No special syntax for defining methods of objects
• Instead, you simply assign a function to a property
27. JavaScript27 www.corewebprogramming.com
Class Methods, Example
• Consider a version of the Ship class that
includes a move method
function degreesToRadians(degrees) {
return(degrees * Math.PI / 180.0);
}
function move() {
var angle = degreesToRadians(this.direction);
this.x = this.x + this.speed * Math.cos(angle);
this.y = this.y + this.speed * Math.sin(angle);
}
function Ship(x, y, speed, direction) {
this.x = x;
this.y = y;
this.speed = speed;
this.direction = direction;
this.move = move;
}
29. JavaScript29 www.corewebprogramming.com
JavaScript Syntax: Objects and
Classes, cont.
5. Arrays
• For the most part, you can use arrays in JavaScript a lot like Java
arrays.
• Here are a few examples:
var squares = new Array(5);
for(var i=0; i<squares.length; i++) {
vals[i] = i * i;
}
// Or, in one fell swoop:
var squares = new Array(0, 1, 4, 9, 16);
var array1 = new Array("fee", "fie", "fo", "fum");
// Literal Array notation for creating an array.
var array2 = [ "fee", "fie", "fo", "fum" ];
• Behind the scenes, however, JavaScript simply represents arrays
as objects with numbered fields
• You can access named fields using either object.field or
object["field"], but numbered fields only via
object[fieldNumber]
30. JavaScript30 www.corewebprogramming.com
Array, Example
var arrayObj = new Object();
arrayObj[0] = "Index zero";
arrayObj[10] = "Index ten";
arrayObj.field1 = "Field One";
arrayObj["field2"] = "Field Two";
makeObjectTable("arrayObj",
arrayObj);
35. JavaScript35 www.corewebprogramming.com
Application: Using JavaScript
to Make Pages Dynamic
• Modifying Images Dynamically
– The document.images property contains an array of
Image objects corresponding to each IMG element in
the current document
– To display a new image, simply set the SRC property of
an existing image to a string representing a different
image file
36. JavaScript36 www.corewebprogramming.com
Modifying Images, Example
• The following function changes the first
image in a document
function changeImage() {
document.images[0].src = "images/new-image.gif";
}
• Referring to images by name is easier:
<IMG SRC="cool-image.jpg" NAME="cool"
WIDTH=75 HEIGHT=25>
function improveImage() {
document.images["cool"].src = "way-cool.jpg";
}
37. JavaScript37 www.corewebprogramming.com
Modifying Images: A Clickable
Image Button, Example
<SCRIPT TYPE="text/javascript">
<!--
imageFiles = new Array("images/Button1-Up.gif",
"images/Button1-Down.gif",
"images/Button2-Up.gif",
"images/Button2-Down.gif");
imageObjects = new Array(imageFiles.length);
for(var i=0; i<imageFiles.length; i++) {
imageObjects[i] = new Image(150, 25);
imageObjects[i].src = imageFiles[i];
}
function setImage(name, image) {
document.images[name].src = image;
}
38. JavaScript38 www.corewebprogramming.com
Modifying Images: A Clickable
Image Button, Example
function clickButton(name, grayImage) {
var origImage = document.images[name].src;
setImage(name, grayImage);
var resetString =
"setImage('" + name + "', '" + origImage + "')";
setTimeout(resetString, 100);
}
// -->
</SCRIPT>
</HEAD>
...
<A HREF="location1.html"
onClick="clickButton('Button1', 'images/Button1-Down.gif')">
<IMG SRC="images/Button1-Up.gif" NAME="Button1"
WIDTH=150 HEIGHT=25></A>
<A HREF="location2.html"
onClick="clickButton('Button2', 'images/Button2-Down.gif')">
<IMG SRC="images/Button2-Up.gif" NAME="Button2"
WIDTH=150 HEIGHT=25></A>
...
39. JavaScript39 www.corewebprogramming.com
Highlighting Images Under the
Mouse, Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>High Peaks Navigation Bar</TITLE>
<SCRIPT TYPE="text/javascript">
<!—
// Given "Foo", returns "images/Foo.gif".
function regularImageFile(imageName) {
return("images/" + imageName + ".gif");
}
// Given "Bar", returns "images/Bar-Negative.gif".
function negativeImageFile(imageName) {
return("images/" + imageName + "-Negative.gif");
}
40. JavaScript40 www.corewebprogramming.com
Highlighting Images Under the
Mouse, Example, cont.
// Cache image at specified index. E.g., given index 0,
// take imageNames[0] to get "Home". Then preload
// images/Home.gif and images/Home-Negative.gif.
function cacheImages(index) {
regularImageObjects[index] = new Image(150, 25);
regularImageObjects[index].src =
regularImageFile(imageNames[index]);
negativeImageObjects[index] = new Image(150, 25);
negativeImageObjects[index].src =
negativeImageFile(imageNames[index]);
}
imageNames = new Array("Home", "Tibet", "Nepal",
"Austria", "Switzerland");
regularImageObjects = new Array(imageNames.length);
negativeImageObjects = new Array(imageNames.length);
// Put images in cache for fast highlighting.
for(var i=0; i<imageNames.length; i++) {
cacheImages(i);
}
41. JavaScript41 www.corewebprogramming.com
Highlighting Images Under the
Mouse, Example, cont.
...
function highlight(imageName) {
document.images[imageName].src = negativeImageFile(imageName);
}
function unHighlight(imageName) {
document.images[imageName].src = regularImageFile(imageName);
}
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<TABLE BORDER=0 WIDTH=150 BGCOLOR="WHITE"
CELLPADDING=0 CELLSPACING=0>
<TR><TD><A HREF="Tibet.html"
TARGET="Main"
onMouseOver="highlight('Tibet')"
onMouseOut="unHighlight('Tibet')">
<IMG SRC="images/Tibet.gif"
NAME="Tibet"
WIDTH=150 HEIGHT=25 BORDER=0>
</A>
...
43. JavaScript43 www.corewebprogramming.com
Making Pages Dynamic:
Moving Layers
• Netscape 4 introduced “layers” – regions
that can overlap and be positioned
arbitrarily
• JavaScript 1.2 lets you access layers via the
document.layers array, each element of
which is a Layer object with properties
corresponding to the attributes of the LAYER
element
• A named layer can be accessed via
document.layers["layer name"] rather
than by using an index, or simply by using
document.layerName
44. JavaScript44 www.corewebprogramming.com
Moving Layers, Example
• Descriptive overlays slowly “drift” to final spot
when button clicked
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Camps on K-3</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function hideCamps() {
// Netscape 4 document model.
document.layers["baseCamp"].visibility = "hidden";
document.layers["highCamp"].visibility = "hidden";
// Or document.baseCamp.visibility = "hidden";
}
function moveBaseCamp() {
baseCamp.moveBy(1, 3);
if (baseCamp.pageX < 130) {
setTimeout("moveBaseCamp()", 10);
}
}
49. JavaScript49 www.corewebprogramming.com
Application: Using JavaScript
to Validate CGI Forms
1. Accessing Forms
– The document.forms property contains an array of
Form entries contained in the document
– As usual in JavaScript, named entries can be accessed
via name instead of by number, plus named forms are
automatically inserted as properties in the document
object, so any of the following formats would be legal
to access forms
var firstForm = document.forms[0];
// Assumes <FORM NAME="orders" ...>
var orderForm = document.forms["orders"];
// Assumes <FORM NAME="register" ...>
var registrationForm = document.register;
50. JavaScript50 www.corewebprogramming.com
Application: Using JavaScript
to Validate CGI Forms, cont.
2. Accessing Elements within Forms
– The Form object contains an elements property that
holds an array of Element objects
– You can retrieve form elements by number, by name
from the array, or via the property name:
var firstElement = firstForm.elements[0];
// Assumes <INPUT ... NAME="quantity">
var quantityField = orderForm.elements["quantity"];
// Assumes <INPUT ... NAME="submitSchedule">
var submitButton = register.submitSchedule;
51. JavaScript51 www.corewebprogramming.com
Checking Form Values
Individually, Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>On-Line Training</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
...
// When the user changes and leaves textfield, check
// that a valid choice was entered. If not, alert
// user, clear field, and set focus back there.
function checkLanguage() {
// or document.forms["langForm"].elements["langField"]
var field = document.langForm.langField;
var lang = field.value;
var prefix = lang.substring(0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "' is not valid.n" +
"Please try again.");
field.value = ""; // Erase old value
field.focus(); // Give keyboard focus
}
}
52. JavaScript52 www.corewebprogramming.com
Checking Form Values
Individually, Example, cont.
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>On-Line Training</H1>
<FORM ACTION="cgi-bin/registerLanguage" NAME="langForm">
To see an introduction to any of our on-line training
courses, please enter the name of an important Web
programming language below.
<P>
<B>Language:</B>
<INPUT TYPE="TEXT" NAME="langField"
onFocus="describeLanguage()"
onBlur="clearStatus()"
onChange="checkLanguage()">
<P>
<INPUT TYPE="SUBMIT" VALUE="Show It To Me">
</FORM>
</BODY>
</HTML>
54. JavaScript54 www.corewebprogramming.com
Checking Values When Form is
Submitted, Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Camp Registration</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function isInt(string) {
var val = parseInt(string);
return(val > 0);
}
function checkRegistration() {
var ageField = document.registerForm.ageField;
if (!isInt(ageField.value)) {
alert("Age must be an integer.");
return(false);
}
...
// Format looks OK. Submit form.
return(true);
}
// -->
</SCRIPT>
55. JavaScript55 www.corewebprogramming.com
Checking Values When Form is
Submitted, Example, cont.
<BODY BGCOLOR="WHITE">
<H1>Camp Registration</H1>
<FORM ACTION="cgi-bin/register"
NAME="registerForm"
onSubmit="return(checkRegistration())">
Age: <INPUT TYPE="TEXT" NAME="ageField"
onFocus="promptAge()"
onBlur="clearStatus()">
<BR>
Rank: <INPUT TYPE="TEXT" NAME="rankField"
onFocus="promptRank()"
onBlur="clearStatus()">
<BR>
Serial Number: <INPUT TYPE="TEXT" NAME="serialField"
onFocus="promptSerial()"
onBlur="clearStatus()">
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit Registration">
</FORM>
</BODY>
</HTML>
57. JavaScript57 www.corewebprogramming.com
Application: Using JavaScript
to Store and Examine Cookies
1. Using document.cookies
– Set it (one cookie at a time) to store values
document.cookie = "name1=val1";
document.cookie = "name2=val2; expires=" + someDate;
document.cookie = "name3=val3; path=/;
domain=test.com";
– Read it (all cookies in a single string) to access values
58. JavaScript58 www.corewebprogramming.com
Application: Using JavaScript
to Store and Examine Cookies
2. Parsing Cookies
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
59. JavaScript59 www.corewebprogramming.com
Cookie, Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Widgets "R" Us</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function storeCookies() {
var expires = "; expires=Monday, 01-Dec-01 23:59:59 GMT";
var first = document.widgetForm.firstField.value;
var last = document.widgetForm.lastField.value;
var account = document.widgetForm.accountField.value;
document.cookie = "first=" + first + expires;
document.cookie = "last=" + last + expires;
document.cookie = "account=" + account + expires;
}
// Store cookies and give user confirmation.
function registerAccount() {
storeCookies();
alert("Registration Successful.");
}
60. JavaScript60 www.corewebprogramming.com
Cookie, Example, cont.
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
function presetValues() {
var firstField = document.widgetForm.firstField;
var lastField = document.widgetForm.lastField;
var accountField = document.widgetForm.accountField;
var cookies = document.cookie;
firstField.value = cookieVal("first", cookies);
lastField.value = cookieVal("last", cookies);
accountField.value = cookieVal("account", cookies);
}
// -->
</SCRIPT>
63. JavaScript63 www.corewebprogramming.com
Application: Using JavaScript
to Interact with Frames
• Idea
– The default Window object contains a frames property
holding an array of frames (other Window objects)
contained by the current window or frame.
• It also has parent and top properties referring to
the directly enclosing frame or window and the top-
level window, respectively.
• All of the properties of Window can be applied to any
of these entries.
64. JavaScript64 www.corewebprogramming.com
Displaying a URL in a Particular
Frame, Example
• ShowURL.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Show a URL</TITLE>
</HEAD>
<FRAMESET ROWS="150, *">
<FRAME SRC="GetURL.html" NAME="inputFrame">
<FRAME SRC="DisplayURL.html" NAME="displayFrame">
</FRAMESET>
</HTML>
65. JavaScript65 www.corewebprogramming.com
Displaying a URL in a Particular
Frame, Example, cont.
• GetURL.html
<HTML>
<HEAD>
<TITLE>Choose a URL</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function showURL() {
var url = document.urlForm.urlField.value;
// or parent.frames["displayFrame"].location = url;
parent.displayFrame.location = url;
}
function preloadUrl() {
if (navigator.appName == "Netscape") {
document.urlForm.urlField.value =
"http://home.netscape.com/";
} else {
document.urlForm.urlField.value =
"http://www.microsoft.com/";
}
}
...
66. JavaScript66 www.corewebprogramming.com
Displaying a URL in a Particular
Frame, Example, cont.
• GetURL.html, cont.
<BODY BGCOLOR="WHITE" onLoad="preloadUrl()">
<H1 ALIGN="CENTER">Choose a URL</H1>
<CENTER>
<FORM NAME="urlForm">
URL: <INPUT TYPE="TEXT" NAME="urlField" SIZE=35>
<INPUT TYPE="BUTTON" VALUE="Show URL"
onClick="showURL()">
</FORM>
</CENTER>
</BODY>
</HTML>
69. JavaScript69 www.corewebprogramming.com
Giving a Frame the Input Focus,
Example
• If JavaScript is manipulating the frames, the
fix is easy: just add a call to focus in
showUrl:
function showURL() {
var url = document.urlForm.urlField.value;
parent.displayFrame.location = url;
// Give frame the input focus
parent.displayFrame.focus();
}
• Fixing the problem in regular HTML
documents is a bit more tedious
– Requires adding onClick handlers that call focus to
each and every occurrence of A and AREA that includes a
TARGET, and a similar onSubmit handler to each
FORM that uses TARGET
70. JavaScript70 www.corewebprogramming.com
Application: Accessing Java
from JavaScript
1. Idea
– Netscape 3.0 introduced a package called LiveConnect
that allows JavaScript to talk to Java and vice versa
– Applications:
• Calling Java methods directly.
– In particular, this section shows how to print
debugging messages to the Java console
• Using applets to perform operations for JavaScript
– In particular, this section shows how a hidden
applet can be used to obtain the client
hostname, information not otherwise available to
JavaScript
• Controlling applets from JavaScript
– In particular, this section shows how
LiveConnect allows user actions in the HTML
part of the page to trigger actions in the applet
71. JavaScript71 www.corewebprogramming.com
Application: Accessing Java
from JavaScript
• Calling Java Methods Directly
– JavaScript can access Java variables and methods simply
by using the fully qualified name. For instance:
java.lang.System.out.println("Hello Console");
– Limitations:
• Can’t perform operations forbidden to applets
• No try/catch, so can’t call methods that throw
exceptions
• Cannot write methods or create subclasses
77. JavaScript77 www.corewebprogramming.com
Accessing JavaScript from
Java
• Steps
1. Obtain and install the JSObject class
– Installed with Netscape 4 (javar40.jar)
– JDK 1.4 includes JSObject in jaws.jar
See Chapter 24 in
http://java.sun.com/j2se/1.4.1/docs/guide/plugin/
developer_guide/contents.html
2. Import it in your applet
import netscape.javascript.JSObject
3. From the applet, obtain a JavaScript reference to the
current window
JSObject window = JSObject.getWindow(this);
78. JavaScript78 www.corewebprogramming.com
Accessing JavaScript from
Java, cont.
• Steps, cont.
4. Read the JavaScript properties of interest
– Use getMember to access properties of the
JSObject
JSObject someForm =
(JSObject)document.getMember("someFormName");
5. Set the JavaScript properties of interest
– Use setMember to set properties of the JSObject
document.setMember("bgColor", "red");
6. Call the JavaScript methods of interest
String[] message = { "An alert message" };
window.call("alert", message);
window.eval("alert(’An alert message’)");
7. Give the applet permission to access its Web page
<APPLET CODE=... WIDTH=... HEIGHT=... MAYSCRIPT>
...
</APPLET>
79. JavaScript79 www.corewebprogramming.com
Matching Applet Background
with Web Page, Example
• MatchColor.java
import java.applet.Applet;
import java.awt.*;
import netscape.javascript.JSObject;
public class MatchColor extends Applet {
public void init() {
JSObject window = JSObject.getWindow(this);
JSObject document =
(JSObject)window.getMember("document");
// E.g., "#ff0000" for red
String pageColor = (String)document.getMember("bgColor");
// E.g., parseInt("ff0000", 16) --> 16711680
int bgColor =
Integer.parseInt(pageColor.substring(1, 7), 16);
setBackground(new Color(bgColor));
}
}
80. JavaScript80 www.corewebprogramming.com
Matching Applet Background
with Web Page, Example, cont.
• MatchColor.html
<HTML>
<HEAD>
<TITLE>MatchColor</TITLE>
</HEAD>
<BODY BGCOLOR="RED">
<H1>MatchColor</H1>
<APPLET CODE="MatchColor.class"
WIDTH=300 HEIGHT=300 MAYSCRIPT>
</APPLET>
</BODY>
</HTML>
82. JavaScript82 www.corewebprogramming.com
Summary
• JavaScript permits you to:
– Customize Web pages based on the situation
– Make pages more dynamic
– Validate HTML form input
– Manipulate cookies
– Control frames
– Integrate Java and JavaScript