Now, lets learn how to make HTML animations with javascript. Consider the following code:
We will build on top of this simple web page. First off, all animations should be relative to a container element. So, we can place a containing element around what we want to animate. For example, we can:
Next, we need to style both the container and the element inside. The container element should be created with style = “position: relative”. The animation element should be created with style = “position: absolute”. Like so:
Animation Code
We can make Javascript animations by making gradual changes in an element’s style. These changes are called by a timer, when the time interval is small, the animation looks continuous. For instance:
setInterval(function, time) calls a function (frame in the example above) every time milliseconds, so above, every 5 milliseconds. setInterval continues calling the function until clearInterval is read in. Now, let’s write the entire code to animate:
JavaScript HTML DOM Events
HTML DOM allows JavaScript to react to HTML events.
Reacting to Events
A javaScript can be executed to react to events, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
Below are examples:
Content changed when user clicks on it:
Function called as event handler
HTML Event Attributes
In order to assign events to HTML elements, we can use event attributes, such as onclick:
We can also assign these events to HTML elements via JavaScript:
The onload and onunload Events
The onload and onunload events are triggered when then user enters or leave the page. The onload event can be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information. We can use the onload and onunload events to load cookies.
Below is an example:
The onchange event
The onchange event is used in combination with the validation of input fields. Once you leave something, say an in input field, a function is called. For instance, the below code capitalizes user input, once the user leaves the input field:
onmouseover and onmouseout
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element. Here is an example:
The onmousedown, onmouseup, and onclick events
The above three events are all mouse click events. When you initially click something, onmousedown is registered, then, when mouse is release, onmouseup is registered. Finally, when the mouse click is complete, onclick is registered. Example: