Basic JavaScript (JS)
While HTML constructs content and CSS decorates layouts, JavaScript acts as the engine that drives your website to life by adding dynamic functionality.
🔗 Injecting JavaScript into HTML
Always inject your JavaScript link directly above the closing </body> tag. This guarantees the browser finishes parsing your visual HTML layout completely before executing script controls:
<!-- Main page content finishes loading above -->
<script src="script.js"></script>
</body>
Fundamental JavaScript Code Snippets
Here are two entry-level methods for adding basic user interactivity on a website:
- Simple Alert Greetings You can instantly trigger notification alert prompts right when a webpage finishes launching:
alert("Welcome to my website! Thank you for visiting.");
- Event Listeners (Making Buttons Work) You can intercept user actions (like clicks) and programmatically alter content styling on the fly:
<!-- HTML Structure -->
<button id="color-btn">Change Heading Color</button>
// JavaScript Interactivity Engine
const button = document.getElementById('color-btn');
const mainHeading = document.querySelector('h1');
// Watch for user clicks to dynamically execute layout changes
button.addEventListener('click', function() {
mainHeading.style.color = 'rgb(113, 161, 211)';
alert("The main heading color has changed dynamically!");
});