Basic Scripting (JavaScript)
Setup
- Go ahead and put the script element within the head element, though it can also go in the body element
- The example code will display "Testing" in the browser console
- The console can be accessed by right clicking, select "Inspect", and then select the "Console" tab
- Text after "//" is a comment for human reading, to be ignored by the browser
- You can make a comment that spans multiple lines by enclosing it between /* and */
- You can put many lines of code in the script element
Running Code With a Button
Code within script element:
Button within page body element:
- When the button is clicked, it will run the code between the curly braces ({ ... }) of the function called 'myFunc'
- A function lets you name block of code so that you can run that code when needed
- The onclick attribute lets you link the function to a page element
- A function can have many lines of code, and you can have many functions in a script element
Linking Script Files
- You can create a script file just by writing JavaScript code in a text file (without the script tags), then save it with a *.js extension
- If the script file is in the same folder as the html file that loads it, you don't have to specify a path, just the file name
- You can add a "defer" attribute (no quotes) after the src="...", it means that the script will not be loaded until after the page has loaded
- You can use "async" instead of "defer" if you want the script to start to execute before the page is done loading
Modifying HTML Elements
- This is just one example of how an element can be selected and modified, there are many other ways
- Here, "document" refers to the whole HTML page, you then can use a selector (e.g. getElementById) to specify which of its elements to work with
- The innerText attribute is for elements that can contain text (such as p, span, button, ...)
- It is useful to use scripts to modify elements in response to user interactions or loaded data
Other Element Attributes to Modify
- When allowing code to modify HTML content, be careful with any values provided by users (some may attempt to inject bad code)
Other Ways to Select Elements
- When you use the "children" selector, it will get the immediate child nodes, so numbering will not include chilren of child nodes
Challenge
Make a simple web page with four buttons and two divs. When the first button is clicked, have it put text in the divs. When the second button is clicked, have it change the text color. When the third button is clicked, make the first div invisible and the second div visible. When the fourth button is clicked, make the second div invisible and the first div visible.