background preloader

Javascript

Facebook Twitter

Why is 'false' used after this simple addEventListener function? Bubbling and capturing. Let’s start with an example. This handler is assigned to <div>, but also runs if you click any nested tag like <em> or <code>: <div onclick="alert('The handler! ')"><em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs. </em></div> Isn’t it a bit strange? Bubbling The bubbling principle is simple. When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. Let’s say, we have 3 nested elements FORM > DIV > P with a handler on each of them: A click on the inner <p> first runs onclick: On that <p>.Then on the outer <div>.Then on the outer <form>.And so on upwards till the document object.

So if we click on <p>, then we’ll see 3 alerts: p → div → form. The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water. Almost all events bubble. The key word in this phrase is “almost”. For instance, a focus event does not bubble. Event.target Check it out: <! Document Object Model (DOM) Level 3 Events Specification. Status of This Document This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at This document is a Working Draft of the Document Object Model Level 3 Events (DOM3 Events) specification. It is expected that this specification will progress to W3C Recommendation status after review and refinement.

This document is produced by the Web Applications WG, part of the Rich Web Clients Activity in the W3C Interaction Domain. You can find the latest Editor's Draft of this document in the W3C's Mercurial repository, which is updated on a regular basis. Implementers should be aware that this document is not stable.

This document was published by the Web Applications Working Group as a Working Draft. This document is governed by the 1 August 2014 W3C Process Document. 3. Note. EventTarget.addEventListener. The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest). Syntax target.addEventListener(type, listener[, useCapture]); target.addEventListener(type, listener[, useCapture, wantsUntrusted ]); // Gecko/Mozilla only type A string representing the event type to listen for. listener The object that receives a notification when an event of the specified type occurs.

UseCapture Optional If true, useCapture indicates that the user wishes to initiate capture. Note: For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6.

WantsUntrusted Example Add a simple listener HTML Content JavaScript Content Notes. James Long. Controlling CSS Animations and Transitions with JavaScript. The following is a guest post by Zach Saucier. Zach wrote to me telling me that, as a frequenter on coding forums like Stack Overflow, he sees the questions come up all the time about controlling CSS animations with JavaScript, and proved it with a bunch of links. I've had this on my list to write about for way too long, so I was happy to let Zach dig into it and write up this comprehensive tutorial. Web designers sometimes believe that animating in CSS is more difficult than animating in JavaScript. While CSS animation does have some limitations, most of the time it's more capable than we give it credit for! Not to mention, typically more performant. Coupled with a touch of JavaScript, CSS animations and transitions are able to accomplish hardware-accelerated animations and interactions more efficiently than most JavaScript libraries.

Let's jump straight in! Quick Note: Animations and Transitions are Different In this article we will cover each of them separately. Manipulating CSS Matrixes. Making Sprite-based Games with Canvas. The web is everywhere, and offers a very powerful and non-traditional environment for creating and distributing apps.

Instead of the code-compile-run cycle, simply refresh your app or even write code live within the browser. Additionally, it's relatively painless to distribute your app across a huge number of platforms. It's exciting that in the past few years, developing games using HTML5, the technology behind the web, has become a reality. The canvas element was introduced with HTML5 and provides an API for rendering on the web. The API is simple, but if you've never done graphics work before it might take some getting used to.

It has great cross-browser support at this point, and it makes the web a viable platform for games. Using canvas is simple: just create a <canvas> tag, create a rendering context from it in javascript, and use methods like fillRect and drawImage on the context to render shapes and images. This is the game we're going to make (play it here). Gearing Up Game Loop. Controlling CSS Animations and Transitions with JavaScript. Create a Sprite Animation with HTML5 Canvas and JavaScript. By William Malone Sprite animations can be drawn on HTML5 canvas and animated through JavaScript. Animations are useful in game and interactive application development. Several frames of an animation can be included in a single image and using HTML5 canvas and JavaScript we can draw a single frame at a time.

This tutorial will describe how HTML5 sprite animations work. We will go step by step through the process of creating a sprite animation. At the end of the this article we will use the animation we created in a simple HTML5 game. The example code is based off the game development framework: BlocksJS. What is a Sprite Animation? Two dimensional frame-based animation can be achieved on HTML5 canvas by rendering an area of a single image on a given interval. Using the drawImage method of the canvas context we can change the source position to only draw a cropped portion of one image called a "sprite sheet". What is a Sprite Sheet? Now Let's Create a Sprite Animation DrawImage Method Render. Create a Game Character with HTML5 and JavaScript - Part 1. By William Malone In Part 1 of this series we will design a game character from scratch. We will start with a drawing on paper and with the help of JavaScript we will create a breathing, blinking character on HTML5 canvas.

Hopefully by the end of Part 1 you will have the tools and inspiration to create a character of your own. Idea to Pixels First we start with an idea. The next step is to get our idea to pixels. Next we color in the outlines. We are creating a dynamic character so we create our character in distinct parts. Head Hair Torso Legs Left Arm Right Arm Each part is saved as a seperate png image. Draw on HTML5 Canvas With the design of our character complete and in the form of six images, we start the process putting our character on canvas. First we create a new object to hold our image references called images. We want to know when all of the images are loaded so we can begin drawing. During the redraw process the canvas will be cleared and all parts will be redrawn. Eyes Shadow. Getting Started with Web Audio API. Before the HTML5 <audio> element, Flash or another plugin was required to break the silence of the web.

While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications. What follows is a gentle introduction to using this powerful API.

Getting started with the AudioContext An AudioContext is for managing and playing all sounds. A single instance of AudioContext can support multiple sound inputs and complex audio graphs, so we will only need one of these for each audio application we create. The following snippet creates an AudioContext: Loading sounds Playing sounds full source code Volume: Object initializer. Summary Objects can be initialized using new Object(), Object.create(), or using the literal notation (initializer notation). An object initializer is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). Syntax New notations in ECMAScript 6 Please see the compatibility table for support for these notations. Description An object initializer is an expression that describes the initialization of an Object. Creating objects An empty object with no properties can be created like this: var object = {}; However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces.

Accessing properties Once you have created an object, you might want to read or change them. Object.foo;object["age"]; object.foo = "baz"; Property definitions We have already learned how to notate properties using the initializer syntax. Var a = "foo", b = 42, c = {};var o = { a, b, c }; Values, variables, and literals. This chapter discusses values that JavaScript recognizes and describes the fundamental building blocks of JavaScript expressions: variables, constants, and literals. Values JavaScript recognizes the following five types of primitive values: Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. Objects and functions are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform. Data type conversion JavaScript is a dynamically typed language.

And later, you could assign the same variable a string value, for example: answer = "Thanks for all the fish Because JavaScript is dynamically typed, this assignment does not cause an error message. In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. X = "The answer is " + 42y = 42 + " is the answer" Variables Unicode. Working with objects. JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.

Objects overview Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. In JavaScript, an object is a standalone entity, with properties and type. Objects and properties A JavaScript object has properties associated with it. ObjectName.propertyName Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. Var myCar = new Object(); myCar.make = "Ford"; myCar.model = "Mustang"; myCar.year = 1969; myCar.noProperty; Hittest.js (PNG Collision Detection) Criando slideshow do zero com javascript puro. Depois de criar um artigo no devmedia de como criar um slideshow do zero em Jquery sem plugins, recebi vários pedidos para fazer o mesmo com javascript, também pude notar que muitas pessoas estavam com dificuldade em colocar link nas imagens e os botões de anterior/próximo. Veremos neste artigo como criar um slideshow do zero apenas com javascript e uma dose elegante de CSS3, com controladores, legendas e links nas imagens.

Abaixo o resultado final do nosso slide: Resultado final do nosso slide Estrutura HTML Nossa estrutura html é bem simples, veja na listagem 1: Listagem 1 – Estrutura html do slideshow Onde: <figure></figure> –> Figura que será responsável de gerenciar todos os elementos do nosso slide <span class=”next trs”>, <span class=”prev trs”> –> Serão os controladores do nosso slide <div id=”slide”> –> div que abriga as imagens do nosso slide, facilitará nosso controle no javascript <figcaption> –> Legenda do slide, será baseada pelo o atributo “alt” das imagens Let’s go! Estilo CSS.