Dynamic List JavaScript
Step 1: Set up the HTML structure
Create an HTML file (index.html) with the following structure:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Dynamic List Exercise</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<div class=”container”>
<h1>Dynamic List Exercise</h1>
<div>
<input type=”text” id=”newItem” placeholder=”Enter new item”>
<button id=”addItem”>Add Item</button>
</div>
<ul id=”itemList”></ul>
</div>
<script src=”script.js”></script>
</body>
</html>
Explanation HTML:
- Document Type Declaration (DOCTYPE):
- Specifies the HTML version being used.
- HTML Element:
- The root element of the HTML document.
- Head Section:
- Contains metadata like character set and viewport configuration.
- Includes the title of the page and a link to an external stylesheet (styles.css).
- Body Section:
- Contains the main content of the page.
- Container Div:
- Holds the entire content of the exercise.
- Styled with CSS to provide a maximum width, margin, padding, background color, and border radius for aesthetics.
- Heading (h1):
- Displays the title of the exercise.
- Input and Button:
- Allows users to input a new item and add it to the list.
- Styled with CSS for a cohesive look.
- Unordered List (ul):
- Serves as the container for the dynamic list.
- Script Tag:
- Includes the JavaScript file (script.js) to add interactivity.
Step 2: Add some basic styles (styles.css)
Create a CSS file (styles.css) with the following content:
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 600px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px;
border-bottom: 1px solid #ccc;
}
button {
background-color: #4caf50;
color: #fff;
border: none;
padding: 8px 12px;
cursor: pointer;
}
Explanation CSS:
- Body Styling:
- Resets default margin and padding for the body.
- Sets a background color for the entire page.
- Container Styling:
- Limits the maximum width of the container and centers it on the page.
- Provides padding, background color, border radius, and a subtle box shadow for a visually appealing container.
- List Styling:
- Removes default list styling (bullets).
- Styles list items with flex display, space-between alignment, padding, and a bottom border for separation.
- Button Styling:
- Gives a green background color, white text, removes borders, adds padding, and a cursor pointer for the “Add Item” button.
Step 3: Write the JavaScript logic (script.js)
Create a JavaScript file (script.js) with the following content:
document.addEventListener(‘DOMContentLoaded’, function () {
const newItemInput = document.getElementById(‘newItem’);
const addItemButton = document.getElementById(‘addItem’);
const itemList = document.getElementById(‘itemList’);
addItemButton.addEventListener(‘click’, addItem);
function addItem() {
const newItemText = newItemInput.value.trim();
if (newItemText === ”) {
alert(‘Please enter a valid item.’);
return;
}
const listItem = document.createElement(‘li’);
listItem.innerHTML = `
<span>${newItemText}</span>
<button class=”removeBtn”>Remove</button>
`;
const removeButton = listItem.querySelector(‘.removeBtn’);
removeButton.addEventListener(‘click’, removeItem);
itemList.appendChild(listItem);
newItemInput.value = ”;
}
function removeItem() {
const listItem = this.closest(‘li’);
itemList.removeChild(listItem);
}
});
Explanation JavaScript:
- DOMContentLoaded Event:
- Ensures that the JavaScript code runs after the HTML document has been fully loaded.
- Variable Declarations:
- newItemInput: References the input field for entering new items.
- addItemButton: References the button for adding items.
- itemList: References the unordered list where items will be displayed.
- Event Listener (addItemButton):
- Listens for a click on the “Add Item” button and triggers the addItem function.
- addItem Function:
- Retrieves the text from the input field, trims any leading or trailing whitespace.
- Checks if the input is not empty; if empty, displays an alert and returns.
- Creates a new list item (li) with a span for the item text and a remove button.
- Attaches an event listener to the remove button, calling the removeItem function.
- Appends the new list item to the item list and clears the input field.
- removeItem Function:
- Finds the closest parent list item (li) of the clicked remove button.
- Removes the list item from the item list.
Step 4: Explanation
HTML Structure: The HTML sets up a simple structure with an input field, a button to add items, and an unordered list to display items.
CSS Styles: The CSS provides basic styling to make the UI visually appealing.
JavaScript Logic:
- The JavaScript code waits for the DOM to be fully loaded (DOMContentLoaded event).
- It selects the necessary elements from the DOM using getElementById.
- It adds an event listener to the “Add Item” button to trigger the addItem function.
- The addItem function checks if the input is not empty, creates a new list item, appends it to the list, and clears the input field.
- Each list item contains a “Remove” button with an event listener to trigger the removeItem function.
- The removeItem function removes the corresponding list item from the DOM.
Step 5: Testing
Open the index.html file in a web browser. You should see a simple interface to add and remove items from a dynamic list.
- Open the index.html file in a web browser.
- Enter text in the input field and click “Add Item” to see the dynamic list in action.
- Click “Remove” next to any item to remove it from the list.
This exercise covers basic DOM manipulation, event handling, and CSS styling to create a functional and visually appealing dynamic list. It can be a starting point for more advanced exercises or projects involving JavaScript, HTML, and CSS.