110 likes | 132 Views
Learn about running and debugging JavaScript code, accessing HTML elements via the DOM, and creating dynamic content on a webpage. Gain insights on using event listeners and complete a programming exercise to enhance your skills in web development.
E N D
Playing with Javascript Getting loopy Get it? Loopy? Because loops?
But first… • Any questions on your current homework assignment? • Any tricks that were helpful? • Any places you're struggling?
Today • Actually running javascript code • Getting information from javascript to us • Where HTML and javascript collide
Running javascript code • Javascript code, much like css, can either be added to a page or included via filename from an external file • Code is given by a script tag • If you are bringing in an external file, the tag should have no text in it and should have a src attribute set • If you are putting the code directly in the file, you don't need to set any attributes, and the javascript code goes between the open and close tag
console.log() • console.log() is the closest thing we have to a "debug print" statement • Whatever we put in parentheses will be output to the console • Let's see a few examples…
Javascript and DOM access • DOM (Document Object Model) is how javascript has access to the HTML elements that make up a page • It's a tree data structure • Some methods make it easy to choose specific elements to manipulate • Today, this will be document.getElementById()
document.getElementById(id) • Given a string parameter specifying an element id, return the HTMLElement referring to that element • Once we have a HTMLElement, we can play around with it a lot • Let's look at making text show up in a div…
Wait, what? • Javascript code is run when it's encountered in the text of the webpage • If code is placed higher up in the file, elements beneath it in the file aren't visible (since that part hasn't be read yet) • We can tell our code to wait until the page has fully loaded to run…
window.addEventListener("load", … • addEventListener is a function that specifies an action to happen when a specific event occurs • An event can be things like a mouse click, a key press, or the page finishing loading • The second parameter is a function to be called when the event occurs • We can do this with a named or an anonymous function…
Programming exercise! • Write javascript code so that the page has an 8 wide, 4 tall rectangle of * characters • You can use += to append to strings (faster than the .concat() method!) • You can set the element's innerHTML to what you want