This project is a simple front-end application that demonstrates how to dynamically create and insert a styled button into different HTML pages based on the current page's URL. It uses vanilla JavaScript and ES6 modules to organize the code.
The project contains the following files:
home.html: An HTML page that includes a container (<div id="btn">) intended for the "Home" button.login.html: An HTML page that includes a container (<div id="button">) intended for the "Login" button.about.html: An HTML page that loads the main script but does not have a target container, so no button will be rendered.main.js: The main JavaScript file. It checks the current URL path and calls thecreateDynamicButtonfunction with specific parameters if the page ishome.htmlorlogin.html.utility.js: A JavaScript module that exports thecreateDynamicButtonhelper function. This function is responsible for creating the button element, applying styles, and appending it to a specified container element.
- A user opens one of the
.htmlfiles (home.html,login.html, orabout.html) in their browser. - Each HTML file loads
main.jsas a module (<script type="module" src="./main.js"></script>). main.jsexecutes. It imports thecreateDynamicButtonfunction fromutility.js.- It gets the current page's path using
window.location.pathname. - It then checks the path:
- If the path includes
home.html, it callscreateDynamicButton("home", "red", "btn"). Theutility.jsfunction then creates a red button with the text "home" and inserts it into the<div id="btn">inhome.html. - If the path includes
login.html, it callscreateDynamicButton("Login", "green", "button"). Theutility.jsfunction creates a green button with the text "Login" and inserts it into the<div id="button">inlogin.html. - If the page is
about.html, neither condition is met, and no button is created. The script simply logs the path to the console.
- If the path includes
To run this project, you do not need a web server. Simply open any of the following files directly in your web browser:
home.html(will show a red "home" button)login.html(will show a green "Login" button)about.html(will show no button)
The provided code has a few minor typos that should be corrected:
-
In
utility.js:retun;should bereturn;- The error message has typos:
Errror:should beError:andno foundshould benot found. - The error log
console.log(\Errror: Container with Id' ${container} no found.`);incorrectly uses thecontainervariable (which isnull) instead ofContainerId. It should be:console.log(`Error: Container with ID '${ContainerId}' not found.`);`
-
In
main.js:- There is an extra, unmatched closing curly brace
}at the very end of the file which will cause a syntax error.
- There is an extra, unmatched closing curly brace