DOM-manipulation



Testa kodexemplet:

Car Showroom

Available Cars
    Car Details

    Select a car from the list to view details


    Kodexempel

    <div id="outputclasses">
        <h1 class="text-center mb-4">Car Showroom</h1>
        
        <div class="row mb-4">
            <div class="col">
                <div class="input-group">
                    <input type="text" id="searchInput" class="form-control" placeholder="Search by brand or model">
                    <button id="searchBtn" class="btn btn-primary">Search</button>
                </div>
            </div>
            <div class="col">                
                <div class="">
                    <button id="showAll" class="btn btn-outline-secondary">Show All</button>
                    <button id="filterElectric" class="btn btn-outline-success">Electric Only</button>
                    <button id="sortPrice" class="btn btn-outline-primary">Sort by Price</button>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col">
                <div class="card">
                    <div class="card-header">
                        <h5>Available Cars</h5>
                    </div>
                    <div class="card-body p-0">
                        <ul id="carsList" class="list-group list-group-flush rounded-bottom"></ul>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-header">
                        <h5>Car Details</h5>
                    </div>
                    <div id="carDetails" class="card-body">
                        <p class="text-muted m-0">Select a car from the list to view details</p>
                    </div>
                </div>
            </div>
        </div>    
    </div>
    
    <script>        
        const cars = [
            { id: 1, brand: "Toyota", model: "Camry", year: 2020, price: 24000, isElectric: false },
            { id: 2, brand: "Tesla", model: "Model 3", year: 2022, price: 45000, isElectric: true },
            { id: 3, brand: "Ford", model: "Mustang", year: 2021, price: 38000, isElectric: false },
            { id: 4, brand: "BMW", model: "X5", year: 2023, price: 52000, isElectric: true },
            { id: 5, brand: "Honda", model: "Civic", year: 2019, price: 22000, isElectric: false },
        ];
    
        // DOM elements
        const carsList = document.getElementById('carsList');
        const carDetails = document.getElementById('carDetails');
        const searchInput = document.getElementById('searchInput');
        //all buttons
        const searchBtn = document.getElementById('searchBtn');
        const showAllBtn = document.getElementById('showAll');
        const filterElectricBtn = document.getElementById('filterElectric');
        const sortPriceBtn = document.getElementById('sortPrice');
    
        // Display all cars
        function displayCars(carsArray) {
            // Clear the car list
            carsList.innerHTML = '';
            //
            if (carsArray.length === 0) {
                carsList.innerHTML = '<li class="list-group-item">No cars found</li>';
                return;
            }
            // Loop through each car and create a list item
            // Using forEach to iterate over the carsArray
            // Using template literals for better readability
            carsArray.forEach(car => {
                const li = document.createElement('li');
                //
                li.style.cursor = 'pointer';
                //car-item need otherwise the css class is not applied                
                li.className = `list-group-item car-item ${car.isElectric ? 'electric' : 'gas'}`;
                li.innerHTML = `
                    <div>
                        <strong>${car.brand} ${car.model}</strong> (${car.year})
                    </div>
                    <span class="badge bg-${car.isElectric ? 'success' : 'primary'}">
                        ${car.price.toLocaleString()}
                    </span>
                `;
                
                // Add click event to show details
                li.addEventListener('click', () => {
                    showCarDetails(car);                
                    //get all items with class car-item.active                   
                    const activeItems = document.querySelectorAll('.car-item.active');
                    //remove active class from all items/cars
                    // This ensures only one car can be active at a time
                    activeItems.forEach(item => item.classList.remove('active'));
                    //add active class to the clicked item/ car
                    li.classList.add('active');
                    
                });
                // Append the list item to the cars list
                carsList.appendChild(li);
            });//end foreach
        }
    
        // Show car details
        function showCarDetails(car) {
            //innerHTML is used to set the content of the carDetails element
            // Using template literals for better readability
            carDetails.innerHTML = `
                <h4>${car.brand} ${car.model}</h4>
                <ul class="list-group list-group-flush mt-3">
                    <li class="list-group-item"><strong>Year:</strong> ${car.year}</li>
                    <li class="list-group-item"><strong>Price:</strong> ${car.price.toLocaleString()}</li>
                    <li class="list-group-item"><strong>Type:</strong> ${car.isElectric ? 'Electric ⚡' : 'Gasoline ⛽'}</li>
                    <li class="list-group-item"><strong>ID:</strong> ${car.id}</li>
                </ul>
            `;
        }
    
        // Search cars
        function searchCars() {
            // toLowerCase is used to make the search case-insensitive
            // value is used to get user input from input field
            const searchTerm = searchInput.value.toLowerCase();
            //filter is used to create a new array with all elements that pass the test implemented by the provided arrow function
            // In this case, it filters cars based on brand or model
            const filteredCars = cars.filter(car => 
            //includes is used to check if the search term is present in the brand or model
                car.brand.toLowerCase().includes(searchTerm) || 
                car.model.toLowerCase().includes(searchTerm)
            );
            //displayCars is called to update the car list with the filtered results
            displayCars(filteredCars);
        }
    
        // Two  event listeners        
        searchBtn.addEventListener('click', searchCars);
        //keyup event is used to listen for key presses in the search input field
        // If the Enter key is pressed, searchCars function is called 
        searchInput.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') searchCars();
        });
    
        // Show all cars when the "Show All" button is clicked
        showAllBtn.addEventListener('click', () => {
            searchInput.value = '';
            displayCars(cars);
        });
    
        // Filter electric cars when the "Electric Only" button is clicked
        filterElectricBtn.addEventListener('click', () => {
            // filter is used to create a new array with all elements that pass the test implemented by the provided arrow function
            // In this case, it filters out electric cars
            const electricCars = cars.filter(car => car.isElectric);
            displayCars(electricCars);
        });
    
        sortPriceBtn.addEventListener('click', () => {
            // sort is used to sort the elements of an array in place and return the sorted array
            // In this case, it sorts the cars by price in ascending order
            // Using the spread operator to create a copy of the cars array
            // This prevents modifying the original array
            const sortedCars = [...cars].sort((carA, carB) => carA.price - carB.price);
            displayCars(sortedCars);
        });
    
        // Initialize
        displayCars(cars);
    </script>