In this lesson, we are going to be teaching you JavaScript through example, so we are going to be scripting
the Portfolio Site we created earlier. So, in the same folder as your HTML file, create another file script.js, and paste the below code into it.
// Step 6: Introduction to JavaScript
// Step 7: Scripting the button "My Webpage" site
const shareBtn = document.getElementById('shareBtn');
shareBtn.addEventListener('click', () => {
// This logic copies the current URL to the clipboard
const currentUrl = window.location.href;
navigator.clipboard.writeText(currentUrl).then(() => {
// Change button text temporarily to show it worked
shareBtn.innerText = "Link Copied!";
shareBtn.style.backgroundColor = "#00d2ff";
shareBtn.style.color = "#1e1e2f";
setTimeout(() => {
shareBtn.innerText = "Copy My Profile Link";
shareBtn.style.backgroundColor = "transparent";
shareBtn.style.color = "#00d2ff";
}, 2000);
});
});
const shareBtn = document.getElementById('shareBtn');
JavaScript needs to "find" the HTML button before it can control it. We use the ID
we
created in
Lesson 1 to grab the button and store it in a variable called shareBtn.
shareBtn.addEventListener('click', () => { ... });
This is like telling a guard: "Wait here, and the moment someone clicks this button, run the code inside these brackets." It’s an Event Listener.
navigator.clipboard.writeText(window.location.href);
This is a powerful browser tool. window.location.href gets your website's URL, and
writeText "pastes" it into the user's computer memory automatically.
shareBtn.innerText = "Link Copied!";
When the link is copied, we change the text on the button so the user knows it worked. This is called User Interface (UI) Feedback.
setTimeout(() => { shareBtn.innerText = "Copy My Profile Link"; }, 2000);
We don't want the button to say "Link Copied" forever. setTimeout tells the brain to
wait for
2000 milliseconds (2 seconds) and then change the text back to normal.