CSCI-1080 Intro To CS: Web Development

Saint Louis University
Department of Computer Science

Intro to Javascript

with javascript we can respond dynamically to user input!

By the end you will be able to:

  1. Write simple JavaScript programs;

  2. Write programs that can respond to user input such as clicking on HTML elements;

  3. Use JavaScript functions;

  4. Use jQuery to manipulate web pages;

  5. Write your own JavaScript functions including anonymous functions

JavaScript Resources

JavaScript is a complex language that would be impossible to teach entirely in a course such as this, but there are many additional resources that you can use to learn more.

This online book is very good:

http://eloquentjavascript.net

The w3schools have good tutorials:

http://www.w3schools.com/js/

as does Mozilla:

https://developer.mozilla.org/en-US/Learn/JavaScript

There are many, many more resources out there and a web search should quickly throw up answers to most questions.

Javascript Idea and General Notions

When a page with only CSS and HTML is requested to a web server, the server simply responds passively. Usually a CSS file is downloaded, several images, and several objects. When instead we ask a query to a webpage containing also a javascript, the javascript being downloaded is responding to the page, from the client's computer, without the need to go ask the server again.

Now we will see how we can interact with webpage locally, using Javascript. Javascript handles events given from the browser, for example clicks, text inputs or window-size changes.

  • HTML and CSS are not programming languages, but markup languages. Javascript is considered instead a real programming language.

  • JavaScript is very different from the Java programming language. JavaScript was originally called ECMAScript.

First Javascript Example: Responding to Mouse Clicks

When you click on an object that has embedded some javascript, something happens! The web browser is creating an event, and I need to create (javascript) code to respond to those events.

Example: Simple way to respond to mouse click events:

<h1 id=“title” onclick=“alert('hello’);”>Hello</h1>

  • onclick is a code that responds when we receive a click event

  • the value within onclick is a script

Let us dissect in details what we saw; consider alert('hello’)

  • alert is a function (a command) with an argument in quote (single quotes). Usually function names are fixed and arguments change the behavior of the function response (the returned value). By the way, the w3schools site documents different JavaScript functions.

  • 'hello’ is an argument that changes the behavior of a function

  • A function is the invariant, the argument is the variant aspect

  • The reason that that argument is in quote is to specify that such argument is a text string. Not all arguments are text strings.

  • Then we got a bunch of punctuation… Programming languages require syntax

    • Parenthesis identify the function

    • The semicolon identifies the end of the command, the end of the function.

  • The onclick attribute says what script should be called when an element is clicked

Now try to build an HTML page that has that code and try to see what happens when you click on the h1 text.

Here is the solution

You have just created the most basic interactive webpage.

You can also create a button that responds to that click, you don't have to necessarily have to use h1 or other tags. Some additional information on onclick can be found on the this page.

The Console

If you use Chrome, open the Javascript console as follows:

View -> Developer -> Javascript Console

The console is useful to send messages out when you are coding and testing things out. Try it by entering in the console

console.log(“hello”);

Now try to include into a website a javascript command that interacts with your console

<body>
	<h1 id="title"
            onclick="console.log('hello');">
            Hello
	</h1>
</body>

See the result here.

Things to note:

  • The console is an object! You will see the term object a lot in “object oriented” programming;

  • log is a function specific of that particular object;

  • The dot links between object and the function;

  • You can manipulate HTML elements by calling functions on objects;

  • Objects represent things in the program, like documents or HTML elements;

  • You can now start coding in javascript using the console as debugging technique.

To summarize so far:

<head>
</head>
<body>
	<!--
 	    In this case the onclick functions
	    writes something to the console.
	    The console is an object so we use the
	    dot (.) notation to call a function
 	    on it
	-->
	<h1 id="title"
 	    onclick="console.log('hello');" >
	    	Hello
	</h1>
</body>

LightBulb Example

Let us know create something fun with the few things we have just learned, elaborating them a little bit more (example taken from w3shools): We want to change the HTML content (an image) after clicking on a button.

To do so, we create two buttons with some javascript embedded in it as follows:

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

So that when we click on one the image change. We need to have an image in our HTML that is labeled myImages:

<img id="myImage" src="pic_bulboff.gif">

Hrere is the code: test it and analyzed it.

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

here are the images if you want to try it on a real webpage:
pic_bulboff.gif
pic_bulbon.gif

Manipulating HTML elements with jQuery

In this course we will be using the Javascript library jQuery to manipulate the so called HTML DOM. The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML and other markup languages like XHTML and XML. The nodes of every document are organized in a tree structure, called the DOM tree.

While it is possible to do this in plain JavaScript, jQuery makes it much easier. JQuery is a javascript library; basically a set of shortcuts you can use to use code someone else has written to make developers life easier.

The main jQuery site and download at https://jquery.com

as well as the jQuery site itself: https://learn.jquery.com

Consider the following code:

  • import of the jquery absolute and relative value

  • min to minified is crunch it down so it access less space

Consider this code:

<h1 id="title" onclick="$('#title').html('Goodbye');">
  • $ is a shorthand for jQuery

  • #title is a selector

  • the action that this code execute is to change the HTML content of title into the other content within the function html(), in the case below, it replaces hello with goodbye once clicked.

<head>
   <!-- to use jQuery we need to import it like this -->
   <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
	<!--
 		in this example use use jQuery to
 	        change the content itself.
  	        The $ is shorthand for the jQuery function
		 We are passing in a CSS selector which
		 gets this element by its id.
		 The html function sets the html content
		 of an element
	-->
	<h1 id="title" onclick="$('#title').html('Goodbye');">
 		Hello
 	</h1>
</body>

See this code working on this separate page.

Script Tag

For these few examples, the code is minimal, but in general, we want to write complex but organized javascript, so we don't want to write code in an attribute. Instead, we should use the Script Tag as follows.

<script type="text/javascript">
	$('#title').html('Goodbye');
</script>

Create your own function

This below is an example of a function

function sayHello(){
	$('#title').html('Goodbye');
};
  • sayHello is the name of our function

  • it does not have any parameter in it

  • a jquery object is called using the dollar sign, and the function html is called with the parameter string Goodbye.

Remember that the library jquery needs to be called inside the head as follows:

<head>
       <script src = "http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

Note the “min”. It is used to minimize the code. When you write complex code using spaces and identation, the min function compact everything into the least possible text, for browser optimization. We do not want to load (in production code) slow HTML (spaces and return lines are characters too, but they are not used so we should not carry them around the network)

To summarize:

<head>
       <script src = "http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
	<h1 id="title" onclick="sayHello()"> Hello </h1>
</body>
<!--
 	the script tag is where you can put
 	more complex scripts
-->
<script type="text/javascript">

	function sayHello() {
		alert('Hello');
	};
</script>

See this code in action on a separate webpage here.

Anonymous function

A function that has another function as argument cannot be done in other programming languages like java or python

This example below is an anonymous function that restores back the text Hello after it was changed into Goodbye with a former click.

<head>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

</head>

<body>
    <h1 id="title" onclick="sayGoodbye();"> Hello </h1>
</body>

<script type="text/javascript">
    function sayGoodbye(){
        console.log("goodbye");
        $("#title").html("Goodbye");
        $("#title").click(function () {
            $("#title").html("Hello");
            $("#title").off("click");
        });
    };
</script>




The contect of this site is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.