← BIT 203 Web Application Development
JavaScript and the DOM
Notes
State and document interaction
JavaScript adds behaviour through variables, expressions, functions and control flow. The Document Object Model, or DOM, represents a page as objects that scripts can inspect and change. Selecting a button retrieves an element object, while adding an event listener specifies what should happen when an event occurs. Keep application state, such as quantities and selected products, distinct from displayed text. Convert input strings explicitly before arithmetic, and handle missing or invalid values rather than relying on implicit conversions that can produce concatenation or unexpected results.
Events and safe updates
An event is a notification of an interaction or system occurrence, such as a click or form submission. Events can bubble from a child element to ancestors, enabling delegation from a shared container. A form submit handler can prevent default navigation while validation and submission occur. Update plain user-provided text with textContent rather than interpreting it as HTML, reducing injection risk. Asynchronous operations complete later, so interfaces should show loading states, handle errors and prevent accidental duplicate submissions. Client-side checks support usability but never replace server-side authorisation and validation.
Practical example
A Kisumu wholesale shop creates a browser order calculator. A customer enters quantity 4 and unit price KES 750. The script converts both input values to numbers and calculates 4 times 750 = KES 3,000. A five percent discount is 0.05 times 3,000 = KES 150, so the displayed payable amount is KES 2,850. If quantity is minus 2, the handler shows an error instead of generating a negative order. During submission, disabling the submit button reduces repeated clicks, while a server-side idempotency key ensures a retried request does not create two orders.
Quiz
1. Which update is safer for displaying an untrusted customer name as plain text?
2. Why explicitly convert numeric form values before arithmetic?
3. What is payable after a five percent discount on KES 3,000?
Sign in to submit and securely grade your quiz.