Home  >  Article  >  Web Front-end  >  Amazing Things You Can Do With Simple JavaScript

Amazing Things You Can Do With Simple JavaScript

王林
王林Original
2024-08-06 22:59:42379browse

Amazing Things You Can Do With Simple JavaScript

JavaScript is a fairly flexible language that can be used to create everything from straightforward server-side systems to intricate online apps. Both inexperienced and seasoned developers love it for its versatility and simplicity of usage. This post will go over 10 incredible things you can do with basic JavaScript, along with code snippets and resources to help you learn more.

  1. Create Interactive Web Pages

JavaScript is essential for adding interactivity to web pages. You can create dynamic content, handle user events, and update the DOM without reloading the page.

Example: Toggle Dark Mode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode Toggle</title>
    <style>
        body {
            transition: background-color 0.3s, color 0.3s;
        }
        .dark-mode {
            background-color: #121212;
            color: #ffffff;
        }
    </style>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <button id="toggle-dark-mode">Toggle Dark Mode</button>
    <script>
        const button = document.getElementById('toggle-dark-mode');
        button.addEventListener('click', () => {
            document.body.classList.toggle('dark-mode');
        });
    </script>
</body>
</html>

References:

MDN Web Docs: Document Object Model (DOM)

JavaScript.info: Introduction to Events

  1. Build Simple Games

JavaScript can be used to create engaging games directly in the browser. With the HTML5 canvas element, you can draw graphics and animate objects.

Example: Basic Snake Game

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <style>
        canvas {
            display: block;
            margin: auto;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const grid = 20;
        let snake = [{ x: 160, y: 160 }];
        let direction = 'right';
        let food = { x: 200, y: 200 };

        function update() {
            const head = { ...snake[0] };
            switch (direction) {
                case 'up': head.y -= grid; break;
                case 'down': head.y += grid; break;
                case 'left': head.x -= grid; break;
                case 'right': head.x += grid; break;
            }
            snake.unshift(head);
            if (head.x === food.x && head.y === food.y) {
                food.x = Math.floor(Math.random() * canvas.width / grid) * grid;
                food.y = Math.floor(Math.random() * canvas.height / grid) * grid;
            } else {
                snake.pop();
            }
        }

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'green';
            snake.forEach(segment => ctx.fillRect(segment.x, segment.y, grid, grid));
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x, food.y, grid, grid);
        }

        function loop() {
            update();
            draw();
            setTimeout(loop, 100);
        }

        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp': direction = 'up'; break;
                case 'ArrowDown': direction = 'down'; break;
                case 'ArrowLeft': direction = 'left'; break;
                case 'ArrowRight': direction = 'right'; break;
            }
        });

        loop();
    </script>
</body>
</html>

References:

MDN Web Docs: Canvas API

JavaScript.info: Keyboard Events

  1. Fetch and Display Data from APIs

JavaScript makes it easy to fetch data from APIs and display it dynamically on your web pages. This is especially useful for creating interactive dashboards and real-time applications.

Example: Display Weather Data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <h1>Weather App</h1>
    <input type="text" id="city" placeholder="Enter city">
    <button id="getWeather">Get Weather</button>
    <div id="weather"></div>
    <script>
        document.getElementById('getWeather').addEventListener('click', () => {
            const city = document.getElementById('city').value;
            fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`)
                .then(response => response.json())
                .then(data => {
                    const weatherDiv = document.getElementById('weather');
                    weatherDiv.innerHTML = `
                        <h2>${data.name}</h2>
                        <p>${data.weather[0].description}</p>
                        <p>Temperature: ${(data.main.temp - 273.15).toFixed(2)} °C</p>
                    `;
                })
                .catch(error => console.error('Error fetching data:', error));
        });
    </script>
</body>
</html>

References:

MDN Web Docs: Fetch API

OpenWeather API

  1. Form Validation

Client-side form validation can be easily handled with JavaScript, providing immediate feedback to users and reducing the need for server-side validation.

Example: Simple Form Validation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation</title>
</head>
<body>
    <form id="myForm">
        <label for="username">Username:</label>
        <input type="text" id="username" required>
        <span id="usernameError" style="color: red;"></span>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" required>
        <span id="emailError" style="color: red;"></span>
        <br>
        <button type="submit">Submit</button>
    </form>
    <script>
        document.getElementById('myForm').addEventListener('submit', function (e) {
            e.preventDefault();
            let valid = true;
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;

            if (username.length < 5) {
                valid = false;
                document.getElementById('usernameError').textContent = 'Username must be at least 5 characters';
            } else {
                document.getElementById('usernameError').textContent = '';
            }

            const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
            if (!emailPattern.test(email)) {
                valid = false;
                document.getElementById('emailError').textContent = 'Invalid email address';
            } else {
                document.getElementById('emailError').textContent = '';
            }

            if (valid) {
                alert('Form submitted successfully!');
            }
        });
    </script>
</body>
</html>

References:

MDN Web Docs: Client-side Form Validation

JavaScript.info: Forms, Controls

  1. Create Animations

JavaScript, along with CSS, allows you to create smooth animations on your web pages. This can be used to enhance user experience and make your site more engaging.

Example: Fade In Effect

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fade In Effect</title>
    <style>
        #fadeInElement {
            opacity: 0;
            transition: opacity 2s;
        }
        .visible {
            opacity: 1;
        }
    </style>
</head>
<body>
    <h1>Fade In Effect</h1>
    <div id="fadeInElement">Hello, World!</div>
    <button id="fadeInButton">Fade In</button>
    <script>
        document.getElementById('fadeInButton').addEventListener('

click', () => {
            document.getElementById('fadeInElement').classList.add('visible');
        });
    </script>
</body>
</html>

References:

MDN Web Docs: CSS Transitions

JavaScript.info: Animation

  1. Build Single Page Applications (SPAs)

JavaScript frameworks like React, Angular, and Vue allow you to build single-page applications that provide a seamless user experience.

Example: Simple SPA with Vanilla JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple SPA</title>
    <style>
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <nav>
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
    </nav>
    <div id="content"></div>
    <script>
        const routes = {
            home: '<h1>Home Page</h1><p>Welcome to the home page.</p>',
            about: '<h1>About Page</h1><p>This is the about page.</p>',
            contact: '<h1>Contact Page</h1><p>Get in touch through the contact page.</p>'
        };

        function navigate() {
            const hash = window.location.hash.substring(1);
            document.getElementById('content').innerHTML = routes[hash] || routes.home;
        }

        window.addEventListener('hashchange', navigate);
        navigate();
    </script>
</body>
</html>

References:

MDN Web Docs: Single Page Applications

JavaScript.info: Location and History

  1. Enhance Accessibility

JavaScript can be used to improve the accessibility of your web applications, ensuring they are usable by everyone, including people with disabilities.

Example: Skip to Content Link

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Skip to Content</title>
    <style>
        #mainContent {
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <a href="#mainContent" id="skipToContent">Skip to Content</a>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
    <main id="mainContent">
        <h1>Main Content</h1>
        <p>This is the main content of the page.</p>
    </main>
    <script>
        document.getElementById('skipToContent').addEventListener('click', function (e) {
            e.preventDefault();
            document.getElementById('mainContent').focus();
        });
    </script>
</body>
</html>

References:

MDN Web Docs: Accessibility

W3C Web Accessibility Initiative (WAI)

  1. Create Browser Extensions

JavaScript can be used to develop browser extensions that enhance the functionality of your browser, automate tasks, and integrate with other services.

Example: Simple Chrome Extension

Create a manifest.json file:

{
    "manifest_version": 2,
    "name": "Hello World Extension",
    "version": "1.0",
    "description": "A simple hello world Chrome extension",
    "browser_action": {
        "default_popup": "popup.html"
    }
}

Create a popup.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <button id="clickMe">Click Me</button>
    <script>
        document.getElementById('clickMe').addEventListener('click', () => {
            alert('Hello from your Chrome Extension!');
        });
    </script>
</body>
</html>

References:

Chrome Developers: Getting Started with Chrome Extensions

MDN Web Docs: Browser Extensions

  1. Automate Tasks with Node.js

JavaScript can also be used on the server-side with Node.js to automate repetitive tasks, such as file manipulation, web scraping, and data processing.

Example: Read and Write Files

Create a file named app.js:

const fs = require('fs');

const content = 'Hello, World!';
fs.writeFile('hello.txt', content, (err) => {
    if (err) throw err;
    console.log('File written successfully');

    fs.readFile('hello.txt', 'utf8', (err, data) => {
        if (err) throw err;
        console.log('File content:', data);
    });
});

Run the script with Node.js:

node app.js

References:

Node.js Official Website

MDN Web Docs: File System

  1. Implement Machine Learning

With libraries like TensorFlow.js, you can implement machine learning models directly in the browser using JavaScript.

Example: Simple Image Classification

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Classification</title>
</head>
<body>
    <h1>Image Classification</h1>
    <input type="file" id="imageUpload" accept="image/*">
    <div id="result"></div>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
    <script>
        const imageUpload = document.getElementById('imageUpload');
        const result = document.getElementById('result');

        imageUpload.addEventListener('change', async () => {
            const file = imageUpload.files[0];
            const img = new Image();
            img.src = URL.createObjectURL(file);

            img.onload = async () => {
                const model = await mobilenet.load();
                const predictions = await model.classify(img);
                result.innerHTML = predictions.map(p => `${p.className}: ${p.probability.toFixed(2)}`).join('<br>');
            };
        });
    </script>
</body>
</html>

References:

TensorFlow.js

MDN Web Docs: File API

Conclusion

There are many uses for JavaScript, making it a versatile and potent language. The possibilities are unlimited, ranging from developing single-page applications and automating processes with Node.js to making simple games and interactive web pages. You may begin exploring these incredible things you can accomplish with basic JavaScript by using the examples and resources provided. Have fun with coding!

Additional References:

JavaScript.info

Eloquent JavaScript

MDN Web Docs: JavaScript

The above is the detailed content of Amazing Things You Can Do With Simple JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn