CIT190 - JavaScript Programming
There are three ways to handle events in JavaScript:
1. HTML attribute
2. DOM property
3. DOM methods: event listeners and event handlers
So far, we have used HTML attributes to handle simple button events and the loading of the page (<body> events). You could use the "on" events in any html element. The problem with this technique is that many programmers have placed the "on" events in a variety of HTML elements, so they are not just used for buttons and page loading. This practice violates progressive enhancement (keeping HTML, CSS and JavaScript separate). Because of this, handling events as HTML attributes is NOT the current standard for best practice and we will not be handling events that way moving forward.
We will be covering how to use DOM properties and DOM event listeners/handlers to deal with events (they are considered best practice for event handling). Many languages have been using event listeners/handlers for years - it is part of the ECMAScript standards. What you will be learning is applicable to other client side languages and JavaScript frameworks (they all incorporate some type of event listener and event handler.)
We will begin by exploring the old and new ways of handling events. Next, we will take a closer look at the event object that is created when events occur. FInally, we will take a look at the variety of events available in the BOM and DOM and how they can be used.
To see a video explaination of the Event Overview, Event Attributes and Events as DOM properties(sections 1 and 2a), see: https://youtu.be/t8jdDDPRX1E
JavaScript events occur in three parts:
1) the event happens and an event object is created
2) the event is recognized or "heard"
3) appropriate action is taken to respond to the event
Binding occurs when you indicate which event you are waiting for and which element that event will affect.
An Event Listener watches out for the event to occur and calls or triggers code that responds to (or handles) the event.
An Event Handler is a block of code (usually a user-defined JavaScript function) that will be run when the event fires.
When you create a block of code to respond to an event, you are "registering" an event handler.
Example with an HTML attribute, onclick, event handler:
<button type="button" id="colorfulButton" onclick="changeColor();">Click to
change button colors!</button></p>
<script>
function random(number) {
return Math.floor(Math.random()*(number+1));
}
function changeColor(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.getElementById("colorfulButton").style.backgroundColor = rndCol;
}
</script>
Having onclick call the changeColor() function registers the event handler.
Here's the example live:
To view it in a separate file, see: testingbutton.html
Placing code inside an HTML element as an attribute is the old way of handling events. Newer preferred methods include:
1. Using DOM properties
2. Using DOM listener methods and called functions
Here's the same example as above using DOM properties and functions. You can use named functions OR anonymous functions. Anonymous functions are simply functions without a name.
Example with an Anonymous Function:
A few things to note include:
a) there is no onclick event in the HTML button element which makes the HTML in alignment with progressive enhancement
b) the onclick event is being registered to the function using the DOM property: document.getElementById("colorfulButton2").onclick=function()
c) the function doesn't have a name (it is "anonymous")
<button type="button" id="colorfulButton2">Click to change button
colors!</button>
<script>
function random(number) {
return Math.floor(Math.random()*(number+1));
}
document.getElementById("colorfulButton2").onclick = function(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.getElementById("colorfulButton2").style.backgroundColor = rndCol;
}
</script>
Here's the example live:
Could we code the DOM property example using a named function?
The answer is YES - it's a matter of coding style and preferences.
Example with a named function:
A few things to be aware of when coding this way include:
a) You need to register the event with the handler indicating you will be using a named function. The statement below handles that:
document.getElementById("colorfulButton3").onclick = changeMe();
b) The function itself, is coded like normal
<button type="button" id="colorfulButton3">Click to change button
colors!</button>
<script>
function random(number) {
return Math.floor(Math.random()*(number+1));
}
document.getElementById("colorfulButton3").onclick = changeMe();
function changeMe(){
var rndCol = 'rgb('
+ random(255) + ',' + random(255) + ',' + random(255) + ')';
document.getElementById("colorfulButton3").style.backgroundColor = rndCol;
}
</script>
Here's the example live:
To view it in a separate file, see: testingbutton2.html
To see a video explanation of sections 2b - using nodelists with DOM properties and section 3 - Events and the addEventListener method, see: https://youtu.be/CoQ3eAv-gp4
In the previous examples we used getElementById to target the elements we wanted to change with the DOM properties. You can also use NodeLists generated by getElementsByTagName, getElementsByClass or querySelectorAll
To use NodeLists, you will need to subscript into the list to target the element you want to change.
Example using getElementsByTagName
a) Notice that none of the buttons have IDs
b) Each button is registered to an anonymous function. The first function changes background color, the second changes text color and the third changes the button color.
c) To use NodeLists with events, you need to code
it as: document.getElementsByTagName("button")[0].onclick = function(){
NOTE: If you were targeting paragraphs, the tagname would be "p" instead
of "button". You can use this with any of the events (not just
onclick)
<p>Click any button to see the colors randomly change</p>
<button
type="button">Change Background</button>
<button type="button">Change
Text</button>
<button type="button">Change Button Color</button>
<script>
function random(number) {
return
Math.floor(Math.random()*(number+1));
}
document.getElementsByTagName("button")[0].onclick= function(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
document.getElementsByTagName("button")[1].onclick = function() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.color = rndCol;
}
document.getElementsByTagName("button")[2].onclick = function() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.getElementsByTagName("button")[2].style.backgroundColor = rndCol;
}
</script>
Here's the example live:
changingColorsbyTagName.html
Here's the same example using querySelectorAll instead of getElementsByTagName (that is the only difference between the 2 scripts): changingColorsbyQuerySelectorAll.html
IMPORTANT: Using NodeLists isn't the most flexible way to code events because content in your page will probably change and that can affect your lists and subscripting.
A better way of coding events is to use the DOM event listener method along with a function.
The DOM addEventListener() method is used to connect events to HTML elements.
Advantages of using addEventListener() include:
Using event listeners is a 2 step process:
1) define the listener to connect the event to a function
2) define the function that handles the event
Creating a listener registers the event (it also binds the event to the handler). The event handler is the function itself.
Syntax: element.addEventListener(event, function,useCapture);
Where element is document.getElementById("id") OR document.getElementsTagName("tag")[subscript] OR document.querySelectorAll("element")[subscript]. etc.
Where event is the type of event that is occurring (basically the on event without including the o and n, instead of onclick, enter "click" Intead of "onmouseover" enter "mouseover" etc)
Where function is the name of the function you want executed when the event occurs
Where useCapture(optional) is either true or false. useCapture is referring to how the event itself is captured. There are 2 ways of capturing events: Event Bubbling (default) and Event Capturing. Because HTML elements are nested, events often occur on an element that is nested within other elements.
Event Bubbling begins at the innermost element and flows outwards. In the example below, clicking the link will cause the event to bubble upward from the anchor (<a> tag to the <body> and <html> elements
<html>
<body>
<article>
<section>
<p>
<a href="http://www.nmc.edu">NMC</a>
Event Capturing starts at the outermost element and flows inwards. In the example above, clicking the link would cause the event to begin at the <html> element and work it's way down to the <a> anchor tag.
If you want to use Event Bubbling, enter false for useCapture. If you want to use Event Capturing, enter true for useCapture. If you have a lot of event handlers and listeners, capturing events at the parent nodes (the outer nodes) may make your program run faster.
Example with getElementById:
document.getElementById("text").addEventListener("click", changeText);
Example with getElementsByTagName
document.getElementsByTagName("button")[0].addEventListener("click", changeBack);
KEYPOINTS TO NOTE:
1. you do not use the "on" portion of the event, you just enter the event without the letter O and N
2. when entering the function name, do NOT include the parenthesis in the event listener, just enter the name of the function
3. you do NOT need to indicate what the capture method is
Event handler functions are created the SAME WAY as other functions. The only thing that makes them special is they are connected to an event through the event listener.
// event listener using getElementsByTagName
document.getElementsByTagName("button")[0].addEventListener("click",
changeBack);
// event handler
function changeBack(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
To see the getElementsByTagName button example with event listener's and handlers, view: listenersWithGetElementsByTagName.html
//event listener using getElementById
document.getElementById("back").addEventListener("click", changeBack);
//event handler
function changeBack(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
To see the getElementById button example with event listener's and
handlers, view:
listenersWithGetElementById.html
Many programmers like to use anonymous functions with event listeners (you will see this done in many languages including the Java programming language). The advantage of using this technique is that you don't need to create a named function. The function you create is invoked as part of the listener code
Sample code:
<script>
// retrieves random number for color change
// called by
functions to adjust red, green and blue
function random(number) {
return Math.floor(Math.random()*(number+1));
}
// event listeners and
handlers
document.getElementById("back").addEventListener("click",
function(){
var rndCol = 'rgb(' + random(255) + ',' +
random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
});
document.getElementById("text").addEventListener("click", function(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.color = rndCol;
});
document.getElementById("btnColor").addEventListener("click", function(){
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.getElementById("btnColor").style.backgroundColor = rndCol;
});
</script>
To see the live example, view: listenersWithGetElementByIdAndAnonymousFunctions.html
So, when should you use anonymous and when should you use named functions?
You should use named functions if the function is going to be used by other events or function calls.
If the function is NOT going to be used anywhere else, then using an
anonymous function is more efficient and will save you time coding and testing.
What we just covered was the hardest part of event handling. The rest involves becoming familiar with the event object itself (because it contains information about the event) AND learning about the diffferent types of browser (BOM) and document (DOM) events
Events occur in the Browser Object Model (BOM) and in the Document Object
Model (DOM). Events within each model are typically grouped into categories. We
will take a look at the DOM event categories, followed by the BOM event
categories.
To see a video explaination of the event object and it's use in event handlers, see: https://youtu.be/Q7CfQfVwRM4
Event handler functions are automatically passed an event object argument. The primary purpose of the event object is to provide more information about the event itself.
The event object includes properties and methods that contain information about the event. For example, you can tell which mouse button was pressed to trigger the click event, what the current location of the mouse pointer is, which key was pressed in a keyboard event, how far the mouse wheel scrolled and which direction it scrolled in etc.
Some of the more popular properties of the event object are listed in the following table:
| Event Object Property | Description |
| SrcElement | The element that fired the event |
| type | Type of event |
| returnValue | Determines whether the event is cancelled |
| cancelBubble | Can cancel an event bubble |
| clientX | Mouse pointer X coordinate relative to window |
| clientY | Mouse pointer Y coordinate relative to window |
| offsetX | Mouse pointer X coordinate relative to element that fired the event |
| offsetY | Mouse pointer Y coordinate relative to element that fired the event |
| button | Any mouse buttons that are pressed |
| altKey | True if the alt key was also pressed |
| ctrlKey | True if the ctrl key was also pressed |
| shiftKey | True if the shift key was also pressed |
| keyCode | Returns UniCode value of key pressed |
For a comprehensive listing of event objects and properties, view: event-objects-and-properties.html
To access the event properties or methods, we need to code our function arguments and function calls a little differently - we need to include a parameter for the event object which gives the object a name we can use to access the information.
The following examples will include event property code so you can see how it works.
In the example below, the parameter e inside function(e), represents the event object and can be used to access methods and properties of that object In the example, the mouse button pressed, the X coordinate of the mouse and the Y coordinate of the mouse are written to the console log. using the event object e
// event listeners and handlers
document.getElementById("back").addEventListener("click", function(e){
console.log("The " + e.which + " mouse button was selected");
console.log("The mouse is at an X coordinate of " + e.clientX);
console.log("The mouse is at an Y coordinate of " + e.clientY);
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
});
To see the full example, view: accessingEventObjects.html Then press F12 and click the console tab to see the log messges
The example from the book shown below is tracking mouse movement and updating values on the screen
The properties of the event objecvar sx = document.getElementById('sx'); //
Element to hold screenX
var sy = document.getElementById('sy'); // Element to
hold screenY
var px = document.getElementById('px'); // Element to hold pageX
var py = document.getElementById('py'); // Element to hold pageY
var cx =
document.getElementById('cx'); // Element to hold clientX
var cy =
document.getElementById('cy'); // Element to hold clientY
function
showPosition(event) { // Declare function
sx.value =
event.screenX; // Update element with screenX
sy.value =
event.screenY; // Update element with screenY
px.value =
event.pageX; // Update element with pageX
py.value =
event.pageY; // Update element with pageY
cx.value =
event.clientX; // Update element with clientX
cy.value =
event.clientY; // Update element with clientY
}
var el =
document.getElementById('body'); // Get body Element
el.addEventListener('mousemove', showPosition, false); // Move updates positiont
covered in this article are listed in the following table.
Here's a link to the entire program (including the HTML): position.html
The example from the book below is counting down the number of characters entered indicating how many characters are left:
// This example has been updated to fire on the keyup event instead of
keypress
// (on the last line in the event listener) as new text is not in
the textarea until the key is released
var el; // Declare variables
function charCount(e) { // Declare function
var
textEntered, charDisplay, counter, lastkey; // Declare variables
textEntered = document.getElementById('message').value; // User's text
charDisplay = document.getElementById('charactersLeft'); // Counter element
counter = (180 - (textEntered.length)); // Num of chars left
charDisplay.textContent = counter; // Show chars left
lastkey = document.getElementById('lastKey'); // Get last key elem
lastkey.textContent = 'Last key in ASCII code: ' + e.keyCode; // Create msg
}
el = document.getElementById('message'); // Get msg element
el.addEventListener('keyup', charCount, false); // on keyup - call charCount()
Here's a link to the entire program, live: keypress.html
To see a video explaination of how to add the event object to listeners that call functions and to listeners that call functions and send additional arguments to functions, see: https://youtu.be/c1remvOXH_0
In event listeners that call functions, you simply need to pass the event variable (ie object) to the function handling the event. You will need to code the function call a little differently than you did before because it is passing parameters. IMPORTANT: To code the function call, you need to use: function(e) { functionName(e, otherArguments)}; e represents the mouse event (you could use any letter or name for the event, it doesn't have to be e)
//event listener passing event object, e, in the argument list.
document.getElementById("back").addEventListener("click", function(e) {changeBack(e)});
//event handler with event object, e, in the parameter list
function changeBack(e){
console.log("The " + e.which + " mouse button was selected");
console.log("The mouse is at an X coordinate of " + e.clientX);
console.log("The mouse is at an Y coordinate of " + e.clientY);
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
To see a full example, view: accessingEventObjectsPassedToFunctions.html Press F12 and select the console tab to see the messages written to the console log.
If you want to include other parameters in a function call that includes the event object, you simply add the other parameters after the event object placing commas between each one.
Full example (instead of generating random colors, the values are being passed to the event handlers):
<!DOCTYPE html>
<html>
<head>
<title>Simple DOM listener event
handler</title>
</head>
<body>
<p>Click any button to see the colors
randomly change</p>
<button type="button" id="back">Change
Background</button>
<button type="button" id="text">Change Text</button>
<button type="button" id="btnColor">Change Button Color</button>
<script>
// event listeners
document.getElementById("back").addEventListener("click",
function(e) {changeBack(e,241,226,219)});
document.getElementById("text").addEventListener("click", function(e)
{changeText(e,58,60,170)});
document.getElementById("btnColor").addEventListener("click",
function(e) {changeButton(e,176,220,232)});
// event handlers
function changeBack(e,red,green,blue){
console.log(e.srcElement); // button that created the event
var rndCol = 'rgb(' + red + ',' + green + ',' + blue + ')';
document.body.style.backgroundColor = rndCol;
}
function changeText(e,red,green,blue)
{
console.log(e.srcElement); // button that created the
event
var rndCol = 'rgb(' + red + ',' + green + ',' + blue
+ ')';
document.body.style.color = rndCol;
}
function changeButton(e,red,green,blue) {
console.log(e.srcElement); // button that created the event
var rndCol = 'rgb(' + red + ',' + green + ',' + blue + ')';
document.getElementById("btnColor").style.backgroundColor = rndCol;
}
</script>
</body>
</html>
Here's the program live:
passingEventObjectAndParameters.html
To see a video explaination on BOM Properties and events, see: https://youtu.be/hVuZrbaCyGE
There are a lot of DOM and BOM events and properties. We will be taking a look at a few of them. The following link provides a comprehensive listing: DOMandBOMevents.html
There are no official standards for the BOM; however, most browsers include the same type of interactivity because the Document node of the BOM is standardized (the Document node comprises the DOM).
We will take a look at some of the BOM Nodes, their properties and their methods (we will be looking more closely at storage and history in upcoming weeks)
Properties of the window object include: history, frames, location, navigator, screen and document. All global JavaScript objects, functions and variables also become properties of the window object.
Since document is a property of the window object, window.document.getElementById("header") is equivalent to document.getElementById("header")
The windows object has methods and properties you may find useful.
Window methods include:
The setInterval() method is typically used to call a function at specified intervals of time.
The clearInterval() method clears the timer set in the setInterval() method.
setInterval Syntax: var varName = setInterval(function() { function name() }, milliseconds);
1000 milliseconds = 1 second
Example: var updateTime = setInterval( function() { myTimer() }, 1000);
clearInterval Syntax: clearInterval(varName);
Example: clearInterval(updateTime);
In the stop button example below, the time is updated every second.
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this
clock:</p>
<p id="demo"></p>
<button type="button" id="stop">Stop
time</button>
<script>
// myVar calls the myTimer function every second
// the myTimer function updates the current time
var myVar =
setInterval(function(){myTimer()}, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
document.getElementById("stop").addEventListener("click",function(){
clearInterval(myVar);
});
</script>
Here's how it looks live:
A script on this page starts this clock:
setInterval and clearInterval can also be used to animate objects on a page (as we saw last week with the pushpin and unicycle)
setTimeout() calls a function or evaluates an expression after a specified number of milliseconds. The function is only executed 1 time (it doesn't repeat like setInterval)
clearTImeout() clears a timer set with the setTimeout() method.
setTimeout() syntax: var varName = setTimeout(function() { function name() }, milliseconds);
1000 milliseconds = 1 second
Example: var displayDate= setTimeout( function() { today() }, 1000);
clearTimeout() Syntax: clearTimeout(varName);
Example: clearTimeout(displayDate);
Example: datePopup.html
Here's the code used to create the example:
<p><em>Click the first button to display a popup with the date after waiting 5
seconds.</em></p>
<p><em>Click the second button to prevent the popup from
displaying. (You must click it before the 5 seconds are up.)</em></p>
<button
type="button" id="displayDate">Display the Date</button>
<button
type="button" id="stopDate">Stop the Date Popup</button>
<script>
var
today = new Date();
var datePopup;
document.getElementById("displayDate").addEventListener("click", function(){
datePopup = setTimeout(function(){alert(today);}, 5000);
});
document.getElementById("stopDate").addEventListener("click", function(){
clearTimeout(datePopup);
});
Syntax: window.print();
Example:
Here's the code:
<button id="print" type="button">Print</button>
<script>
document.getElementById("print").addEventListener("click",function(){window.print();});
</script>
Syntax: window.open(URL, name, specs, replace);
URL, name, specs and replace are optional. If nothing is specified, a blank window is opened.
URL - the web address of the window you want to open
name - how you want to open the window, values include:
NOTE: You can assign an objectname to the window that you can use to manipulate the window (see example below)
specs - comma separated list of items that specify specify information about the new window (such as height, width, fullscreen, statusbar, scrollbars etc) Values for specs include:
fullscreen=yes or 1 OR no or 0 (default is no)
height=pixels (minimum value is 100)
width=pixels (minimum value is 100)
left=pixels (left position of the window, only positive values are allowed)
location=yes or 1 OR no or 0 (whether to display the address bar or not - only applies to the Opera browser)
menubar==yes or 1 OR no or 0 (whether or not to display the menu bar)
resizable=yes or 1 OR no or 0 (whether or not the window is resizable - only applies to IE)
scrollbars==yes or 1 OR no or 0 (whether or not to display scroll bars - only applies to IE, Firefox and Opera)
status==yes or 1 OR no or 0 (whether or not to add a status bar)
titlebar==yes or 1 OR no or 0 (whether or not to display the title bar - this is ignored unless the calling application is an HTML Application or a trusted dialog box)
toolbar==yes or 1 OR no or 0 (whether or not to display the browser toolbar - only applies to IE and Firefox)
top=pixels (the top position of the window, only positive values are allowed)
replace - whether the URL creates a new entry or replaces the current entry in the history list
true (URL replaces current doc in history list)
false (URL creates a new entry in history)
function openWin() {
myWindow = window.open("", "myWindow",
"width=200, height=100"); // Opens a new window
}
Syntax: window.close();
Example:
var myWindow;
function openWin() {
myWindow = window.open("",
"myWindow", "width=200, height=100"); // Opens a new window
}
function
closeWin() {
myWindow.close(); // Closes the new window
}
Syntax: window.moveTo( xCoord, yCoord); or window.moveBy(xCoord,yCoord);
xCoord is the horizontal position (left position)
yCoord is the vertical position (top position)
Example:
function moveWinTo() {
myWindow.moveTo(150, 150);
myWindow.focus();
}
function moveWinBy() {
myWindow.moveBy(75, 50);
myWindow.focus();
}
Syntax: window.resizeTo(width,height);
where width and height are pixels
Example:
function openWin() {
myWindow = window.open("", "",
"width=100, height=100"); // Opens a new window
}
function resizeWin()
{
myWindow.resizeTo(250, 250); // Resizes the new window
myWindow.focus(); // Sets focus to the new window
}
Example: To see an interactive example with multiple window properties, select: createNewWindow.html (to see the source code, right click and select View Source). NOTE: You will need to create the window first and then you can resize and reposition it :)
Specific properties you can modify using the Window object include:
For additional properties, see: https://www.w3schools.com/jsref/obj_window.asp
To see an example that uses the properties, view: WindowCharacteristicsv2.html (to see the source code, right click and select view source).
Properties include:
screen.width - returns the screen width in pixels
screen.height - returns the
screen height in pixels
screen.availWidth - returns the width minus interface
features like scrollbars
screen.availHeight - returns the height minus
interface features like the taskbar or toolbars
screen.colorDepth -
returns the number of bits used to display 1 color (true colors is either
24 bit or 32 bit; high color is 16 bit and VGA color is 8 bit)
screen.pixelDepth - returns the pixel depth of the screen (for modern
computers the color depth and the pixel depth are the same)
NOTE: You could also prefix each property with window.
Example: To see an interactive example with multiple window properties, select: screenInfo.html (to see the source code, right click and select view source).
There are no specific standards for the history object, but all browsers do support it. There is one property and three methods (functions)
Properties include:
history.length - returns the number of URLs in the history list
Example:
<!DOCTYPE html>
<html>
<body>
<script>
document.write("<p>The number
of URLs in the history list is: " + history.length + "</p>");
</script>
</body>
</html>
Methods include:
window.history.back() - loads previous URL (same as clicking the browser's back button) This won't work if they haven't viewed multiple pages during the current session OR if they are on the first URL in the list For more information, visit: http://www.w3schools.com/jsref/met_his_back.asp
window.history.forward() - loads the next URL (same as clicking the browser's forward button) This won't work if they haven't viewed multiple pages during the current session OR if they are on the most recent URL in the list For more information, visit: http://www.w3schools.com/jsref/met_his_forward.asp
window.history.go(pages) - where pages is the number you want to go forward or backward from the current page (negative numbers go back, positve numbers go foward). For more information, visit: http://www.w3schools.com/jsref/met_his_go.asp
Location Object properties include:
Location Object methods include:
location.assign() - loads a new document
location.reload() - reloads the
current document
location.replace() - replaces the current document
with a new one removing the old document's URL from the history list
To see an interactive example, view: locationInfo.html (to see the source code, right click and select view source). NOTE: If you click on replace page, and then you try to use the back button, it will not take you to the URL info page because it's URL is no longer in the history list. If you click on new page, and then you use the back button, it will take you back to the URL info page because it is still in the list.
The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
1. Different browsers can (and do) use the same name
2. The navigator
data can be changed by the browser owner
3. Some browsers misidentify
themselves to bypass site tests
4. Browsers cannot report new operating
systems, released later than the browser
An example of this is that IE11, Chrome, Firefox, and Safari return an appName "Netscape" and Chrome, Firefox, IE, Safari, and Opera all return appCodeName of "Mozilla".
Navigator Object properties/methods include:
To see an interactive example, view: navigatorInfo.html (to see the source code, right click and select view source).
For a full list of DOM events, view: DOMandBOMevents.html
For a list of DOM Element Properties and Methods view: DOMElementProperties.html
We have spent a great deal of time looking at a variety of DOM and BOM events and properties. We are going to take a look at how to animate DOM objects.
To see a video explaination of the code used to animate DOM objects, see: https://youtu.be/2uOCiQGmD6s
In order to animate anything, you need to place the object you want to animate into a container (that object can be an image or something else).
Example - an image is placed into a container:
<div id ="container">
<img alt="zeppo"
src="media/monkey.png" id ="monkey" />
</div>
Apply styling to the container and the element you plan to animate (in the example below, the element that will be animated is the monkey graphic with an id set to monkey)
#container {
width: 200px;
height:
200px;
position: relative;
}
#monkey {
width: 150px;
height: 150px;
position: relative;
background-color: none;
}
JavaScript animations are done by programming gradual changes in an element's style. The changes can be called by a timer. When the timer interval is small, the animation looks continuous. The setInterval method works well for this type of animation. When you want the animation to stop, you call the clearInterval method
You can setup the animation to start when the page loads or to be triggered by a button or some other event. In the example below, the down button is used to start animation that moves the monkey downward
<section>
<div id ="container">
<img alt="zeppo"
src="media/monkey.png" id ="monkey" />
</div>
</section>
<section>
<p>
<button id="down">Move Zeppo down</button>
<button id="stop">Make Zeppo stop</button>
</p>
</section>
<script>
var id; // keeps track of whether
setInverval is on or off
var posX=0; // used for
horizontal movement
var posY=0; // used for vertical
movement
var elem = document.getElementById("monkey"); //
retrieves the monkey image
// event handler for button with anonymous function
document.getElementById("down").addEventListener("click",function() {
var id = setInterval(frame, 5); // places a value into ID for setInterval
posY=elem.y; // sets current y coordinate position of image into posY
function frame() {
// event listener for the stop button
document.getElementById("stop").addEventListener("click",function(){clearInterval(id);});
// testing to make sure images is still within the background
if (posY>=450) {
clearInterval(id);
} else {
posY++;
elem.style.top = posY + 'px';
}
}
});
Here's the full blown program with buttons that move the monkey up, down, left and right. There is also a button to make the monkey dance and stop moving. In the upperright corner, you will see x and y coordinates indicating where the monkey is currently located within the window: zepposWorld.html
To see another example with a box, view: https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3
For more information, see: https://www.w3schools.com/js/js_htmldom_animate.asp