Week 6 JavaScript 02
Week 6: JavaScript Part 2
1. Object¶
An object is a complex data type that allows you to store collections of data and more complex entities.
Example of Object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
1.1 The Document Object¶
- When an HTML document is loaded in a web browser, it transforms into a document object, serving as the root node of the document.
- This document object is a property of the window object and can be accessed using either
window.document
or simplydocument.
1.2 Properties / Methods in Document Object¶
Property: document.propertyName
- Properties are values that you can obtain or change
Method: document.methodName()
- Methods are actions you can perform on HTML element
Source: https://www.w3schools.com/jsref/dom_obj_document.asp
Exercise 1. Update Time Automatically¶
- Update the year automatically
- Using
document
object,write
method - new Date() creates a new date object with the current date and time at the moment the code is executed.
- .getMonth() get the current year from the date
<p><small>©Copyright ©
<script>document.write(new Date().getMonth() + 1 + '/' + new Date().getFullYear());</script>
Yanan Wu <br> All rights reserved</small></p>
1.3 Change the content of the element¶
Change the property of the
<p>
element with id='location'The most common way to access an element is to use the
id
of the elementThe
innerHTML
is used to get the values of element
2. Events in JS¶
Events are things that happen in the web page you are programming
The user selects, clicks, or hovers the cursor over a certain element
Common events:
onclick
,onmouseover
,onchange
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<element event='some JavaScript'>
Exercise 2: Add events to button¶
onclick
is added to a <button>
element
- Step 1: Create a button
- Step 2: Set up where the message appear
- Step 3: JavaScript to Handle Events
Add JavaScript to make the button functional. This script will listen for the click event and display a message
<button onclick = "document.getElementById('lucky').textContent='You are the BEST One'";>Get your lucky words</button>
<p id = "lucky"></p>
Changes the content of its own element
<button onclick= "this.textContent = Date()" style="height: 100px;font-size: large;">The current date and time</button>
3. Back To Top Button¶
The JS accesses the button via document.getElementById()
, attaches an event handler with onclick
, and uses the window.scrollTo()
method to scroll the page to the top. The smooth scrolling effect is achieved by setting behavior: 'smooth'
, enhancing the user experience.
Exercise 3: Back To Top Button¶
- Created using
- Using const to declare the backButton variable to store the reference to the HTML element.
- Using the onclick event to trigger functions based on user interaction
- window.scrollTo(): This method control the scrolling
<div> <button id ="backtoTop">Back To Top</button>
</div>
## store below script in external js
const backButton = document.getElementById('backtoTop');
backButton.onclick = function(){
window.scrollTo({
top: 0,
behavior:'smooth'
})
};
4. Dynamic effect: Add or remove class to a element¶
document.querySelector()
: This method selects the first matching element in the DOM that matches the specified CSS selector. Here, it's used to get the button with the class change_bk.document.querySelectorAll()
: This method returns a NodeList of all elements matching the specified CSS selector. In this case, it selects all<a> tags
within the first<p> tag
of the#p_intro element
.- Variable initialization: let
back_g = true
; - Event Listeners: Assigning an onclick event handler to the changebutton. This allows the function to execute whenever the button is clicked.
forEach()
Method: This array method allows you to execute a function on each element in the NodeList. Here, it's used to iterate over each<a> link
.link
represents one of the<a> elements
selected bydocument.querySelectorAll("#p_intro p a")
.
Exercise 4: Highlight elements¶
- Step 1: Create a button
<button class='change_bk'>Click here to highlight my past experience</button>
- Step 2: Add a potential class
.highlight_e {
background-color: yellow; /* Change to your desired background color */
}
- Step 3: Create dynamic effect to button, add or remove class to elements
const changebutton = document.querySelector(".change_bk");
const past_experience = document.querySelectorAll("#p_intro p a");
let back_g = true;
changebutton.onclick = function(){
past_experience.forEach(link => {
if (back_g){
link.classList.add("highlight_e");
} else{
link.classList.remove("highlight_e");
}
})
back_g = !back_g;
}
- Step 4: Make connection betwen your html and external css or js
Add script and link to your html
Exercise 5. Toggle Effect Between Two elements Using JS and CSS¶
We create an effect that toggles between two header on a webpage. The headers will fade in and out every few seconds
Step 1: HTML Structure¶
Start by defining two headers in your HTML file:
<div class="nav_bar_header1"><h1>Hello</h1></div>
<div class="nav_bar_header2"><h1>I'm a Geospatial Scientist</h1></div>
Step 2: CSS for Transition¶
We will add transitions for a smooth fade effect and make sure only one header is visible at a time
- position: absolute;: This positions the headers relative to their parent container, so they can overlap.
- opacity: 0;: Initially hides the headers.
- transition: opacity 1s ease-in-out;: Adds a smooth fade effect over 1 second when changing the opacity.
.nav_bar_header1, .nav_bar_header2 {
position: absolute;
top: 0;
left: 0;
right: 0;
opacity: 0; /* Initially hidden */
transition: opacity 1s ease-in-out; /* Smooth fade */
}
.show {
opacity: 1; /* Make visible when the .show class is added */
}
Step 3: JavaScript to Toggle Headers¶
Add the JavaScript that makes the headers alternate every few seconds:
- setTimeout method: https://www.w3schools.com/jsref/met_win_settimeout.asp
- The setTimeout() method calls a function after a number of milliseconds.
- 1 second = 1000 milliseconds.
window.onload = function() {
// Get headers
const header1 = document.querySelector(".nav_bar_header1");
const header2 = document.querySelector(".nav_bar_header2");
let isHeader1Visible = true; // Start with header1 visible
// Function to toggle between headers
function toggleHeaders() {
if (isHeader1Visible) {
// Show header1, hide header2
header1.classList.add("show");
header2.classList.remove("show");
} else {
// Show header2, hide header1
header2.classList.add("show");
header1.classList.remove("show");
}
// Switch to the other header for the next cycle
isHeader1Visible = !isHeader1Visible;
// Repeat the toggle every 4 seconds
setTimeout(toggleHeaders, 4000);
}
// Start the toggle cycle
toggleHeaders();
};
Exercise 6: Add dynamic effects to the image¶
Step 1: Create Figure and Pop-up Window
<span> tag
: The<span>
element is a generic container for inline content, used to style or manipulate parts of text or other inline content in HTML without affecting the page's layout structure.×
: This is an HTML entity that represents the multiplication sign (×), which is often used as a symbol for a "close" button, especially in modal dialogs or alerts.
<div class="gallery-item">
<img src="Images\presentation\aag_denver.jpg"
alt="Association of American Geographers Conference" class="gallery-img">
<figcaption style="font-size: 50px;">AAG Conference</figcaption>
</div>
<div class="myPop">
<span class="close">×</span>
<img id="img_pop" style="margin-top: 10rem;">
<h1 id = "h1_pop"></h1>
</div>
Step 2: Set up the CSS style for the Pop-up window
- The
z-index
property specifies the stack order of an element. - Overflow set up the desired window when content does not fit in the element
.myPop{
display: None;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width:100%;
height: 100%;
overflow: auto;
background-color: rgb(252, 252, 252);
text-align: center;
border: solid;
}
Step 3: Set up the CSS style for the close button
.close{
position: absolute;
top: 5rem;
right: 10rem;
color: #0d27d0;
font-size: 10rem;
font-weight: bold;
}
.close:hover,.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
Step 4: Using JS to add dynamic effect
- document.getElementsByClassName("myPop"): This retrieves all elements with the class "myPop" and returns a collection (like an array).
- [0]: The index [0] accesses the first element in the collection. If there's only one element with the class "myPop", that element will be at index 0, which is why you need to use [0] to target it.
- If you omitted [0], you would be trying to manipulate a collection of elements, which would cause an error because methods like style.display are intended for individual elements, not collections.
<script>
// Get the image and insert it inside the modal
const images = document.getElementsByClassName("gallery-img");
const captionText = document.getElementById("caption");
const pop_w = document.getElementsByClassName("myPop")[0];
const pop_Img = document.getElementById("img_pop");
const pop_h1 = document.getElementById("h1_pop")
// Loop through all gallery images
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() {
pop_w.style.display = "block";
pop_Img.src = this.src;
pop_h1.innerHTML = this.alt
}
}
</script>