An 'event' is when something happens. For example when the user mouses over a link in a web page.
element.onmouseover = function () {
//code to execute when the mouse over happens
};
There are variety of events. Some of the most common are:
How do you make an event trigger some code?
You can create a JavaScript event via HTML and call it via JavaScript.
<button id="clickMe" onclick="sayHi()">Click Me!</button>
function sayHi() {
alert ('Hi!');
}
A few things to know.
DOM Events work like many of the other things we have done.
1. Find the object
var myTarget = document.getElementById('clickMe');
2. Then add an event to that object:
myTarget.onclick=function(){
alert ('Hi!');
}
Download this sample code.
Create an alert box when you onmouseover
the turtle image. Try another event of your choice.
This is more of a modern way to work with Events by creating Event Listeners and Event Handlers.
Beware, this may not work in older browsers.
1. Find the object:
var myTarget = document.getElementById('clickMe');
2. Add the Event Listener:
myTarget.addEventListener("click", clickHandler);
3. Add the Event Handler:
function clickHandler(){
alert ('Hi!');
}
Use the previously downloaded sample code.
Create an alert box when you onmouseover
the turtle image using event listeners and event handlers. Try another event listener of your choice.
At times you might have an <a href="#">link</a>
but you don't want to the href to go to another page.
There is a built-in method to handle that:
element.onclick = function (event) {
event.preventDefault();
};
Note the event argument
Write code that targets this link:
<a href="http://girldevelopit.com/" id="gdiLink">Girl Develop It</a>
When a user clicks the link, the page should display an error message instead of going to the Girl Develop It homepage.
You can collect information from users to use in functions. The most common method is an HTML form
<form id="temperatureForm">
<label for="temp">Temperature:</label> <input type="text" id="temp" size="3"/> degrees in
<input type="radio" name="tempFormat" value="F" checked />Fahrenheit
<input type="radio" name="tempFormat" value="C" />Celsius <br />
<label for="submitButton"></label> <input id="tempSubmitButton" type="submit" value="Submit" />
</form>
You retrieve the values of form elements using the value
property.
var temperature = document.getElementById('temp').value;
console.log (temperature);
You can retrieve the value of a form at any time. Try onblur
(when a form element loses focus).
Radio buttons usually do not have IDs, so you will need to use an array:
var radios = document.getElementsByName('tempFormat');
var button = document.getElementById('getValue');
button.addEventListener("click", handleClick);
function handleClick(event){
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
var radioButtonValue = radios[i].value;
// only one radio can be checked, so stop now
alert(radioButtonValue);
break;
}
}
}
If you are going to get form values by clicking the submit button we need to approach things in a different way.
var submitButton = document.getElementById('simpleSubmit');
simpleForm.addEventListener("submit", handleSubmit);
function handleSubmit(event){
var resultsBox = document.getElementById('resultsBox');
var inputValue = document.getElementById('inputValue');
event.preventDefault();
resultsBox.innerHTML = inputValue.value;
}
Collect a value from the input box on the page. Display that value on the page.
The browser automatically builds a Document object of the entire page.
To interact with the page you need to do at least 3 things
You can find nodes by id using the method:
document.getElementById(id);
To find:
<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
We would use:
var imgBear = document.getElementById('bearPic');
console.log(imgBear);
You can find list of elements by Tage Name:
document.getElementsByTagName(tagName);
To find:
<ol>
<li>Daisy</li>
<li>Tulip</li>
</ol>
We would use:
var listItems = document.getElementsByTagName('li');
console.log(listItems);
You can find a list of elements by class Name:
document.getElementsByClassName(className);
To find:
<h2 class="master-headline">My Blog Post</h2>
We would use:
var headline = document.getElementsByClassName('master-headline');
console.log(headline);
Now that the element is stored in a variable, we can access the properties and change them.
You can access and change attributes of DOM nodes using dot notation.
To change this element:
<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
We could change the src attribute this way:
var imgBear = document.getElementById('bearPic');
var oldSrc = imgBear.src;
imgBear.src = 'http://placebear.com/100/500';
You can also use getAttribute/setAttribute
<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
We could change the src attribute this way:
var imgBear = document.getElementById('bearPic');
var oldSrc = imgBear.getAttribute('src');
imgBear.setAttribute('src', 'http://placebear.com/100/500');
The most common properties to change are styles.
To make this style change via JavaScript:
body {
color: red;
}
Use this JavaScript:
var pageNode = document.getElementsByTagName('body')[0];
pageNode.style.color = 'red';
Change any CSS property with a "-" to camelCase, and be sure to include a unit on any number.
To make this style change via JavaScript:
body {
background-color: pink;
padding-top: 10px;
}
Use this JavaScript:
var pageNode = document.getElementsByTagName('body')[0]
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';
Use the previously downloaded sample code.
Isolate a node (an element on the page) and change an attribute or add a new style. Also try a style chnage via a button click.
Each DOM node has an innerHTML
property with the HTML of all its children.
You can use the property to view or change the HTML of a node.
For example, you can overwrite the entire body:
var pageNode = document.getElementsByTagName('body')[0];
pageNode.innerHTML = '<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>'
Or just add some new content to the end
pageNode.innerHTML += '...just adding this bit at the end of the page.';
You can also target a particular element
To fill this HTML element:
<p id="warning"></p>
We can select the node and modify it
var warningParagraph = document.getElementById('warning');
warningParagraph.innerHTML = 'Danger Will Robinson!';
Use the previously downloaded sample code.
Lets spend some time changing and adding text on the screen using innerHTML.
The document
object also provides ways to create nodes from scratch:
document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
var pageNode = document.getElementsByTagName('body')[0];
var newImg = document.createElement('img');
newImg.src = 'http://placebear.com/400/300';
newImg.style.border = '1px solid black';
pageNode.appendChild(newImg);
var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('Squee!');
newParagraph.appendChild(paragraphText);
pageNode.appendChild(newParagraph);
Use the previously downloaded sample code.
Lets spend some time creating brand new HTML using createElement.
jQuery is a fast, small, and feature-rich JavaScript library.
You can find nodes by id using the method:
// VANILLA
document.getElementById(id);
// JQUERY
$(id);
To find:
<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
We would use:
// VANILLA
var imgBear = document.getElementById('bearPic');
// JQUERY
var imgBear_jquery = $('bearPic');
You can find list of elements by Tage Name:
// VANILLA
document.getElementsByTagName(tagName);
// JQUERY
$(tagName);
To find:
<ol>
<li>Daisy</li>
<li>Tulip</li>
</ol>
We would use:
// VANILLA
var listItems = document.getElementsByTagName('li');
// JQUERY
var listItems_jquery = $('li');
You can find a list of elements by class Name:
// VANILLA
document.getElementsByClassName(className);
// JQUERY
$(className);
To find:
<h2 class="master-headline">My Blog Post</h2>
We would use:
// VANILLA
var headline = document.getElementsByClassName('master-headline');
// JQUERY
$('master-headline');
$( "div" ).css( "border", "9px solid red" );
It's handy, has a consistent syntax, and is known for cross browser implementation.
Now it's time for you to go out a build something! You now have the knowledge to: