0% found this document useful (0 votes)
17 views62 pages

Lecture 7 User Interfaces

Uploaded by

gegeni5226
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views62 pages

Lecture 7 User Interfaces

Uploaded by

gegeni5226
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

IS424

Lecture 7

User Interfaces
Outline

Part 1 Part 2 Part 3


Pa
• Introduction • Animation using CSS • React rt
• User Interfaces
2
 Introduction.

• Single Page Applications  Addition example.

• Scroll

 Infinite Scroll
Part 1
Introduction

• So far, we’ve discussed how to build simple web pages using HTML and CSS, and how to use Git and

GitHub in order to keep track of changes to our code and collaborate with others. We also familiarized

ourselves with the Python programming language, started using Django to create web applications, and

learned how to use Django models to store information in our sites. We then introduced JavaScript and

learned how to use it to make web pages more interactive.

• Today, we’ll discuss common paradigms in User Interface design, using JavaScript and CSS to make our

sites even more user friendly.


User Interfaces

• A User Interface is how visitors to a web page interact with that page.

• Our goal as web developers is to make these interactions as pleasant as possible for the user,

and there are many methods we can use to do this.


Single Page Application

• Previously, if we wanted a website with multiple pages, we would accomplish that using

different routes in our Django application.

• Now, we have the ability to load just a single page and then use JavaScript to manipulate the

DOM

• One major advantage of doing this is that we only need to modify the part of the page that

is actually changing.

• For example, if we have a Nav Bar that doesn’t change based on your current page, we wouldn’t

want to have to re-render that Nav Bar every time we switch to a new part of the page.
Single Page Application

• Let’s look at an example of how we could


simulate page switching in JavaScript:
• Notice that we have three buttons and three
divs.
• At the moment, the divs contain only a small bit
of text, but we could imagine each div
containing the contents of one page on our
site.
Single Page Application

• Now, we’ll add some JavaScript that allows us to use the buttons to toggle between pages.
Single Page Application

• In many cases, it will be inefficient to load the entire contents of every page when we first visit a
site, so we will need to use a server to access new data.
• For example, when you visit a news site, it would take far too long for the site to load if it had to
load every single article it has available when you first visit the page.
• We can avoid this problem using a strategy similar to the one we used while loading currency
exchange rates in the previous lecture.
• This time, we’ll take a look at using Django to send and receive information from our single page
application. To show how this works, let’s take a look at a simple Django application. It has two
URL patterns in urls.py:
Single Page Application

• And two corresponding routes in views.py. Notice that the section route takes in an integer,
and then returns a string of text based on that integer as an HTTP Response.
Single Page Application

• Now, within our index.html file, we’ll take advantage of


AJAX, which we learned about last lecture, to make a
request to the server to gain the text of a particular
section and display it on the screen:

• Now, we’ve created a site where we can load new data


from a server without reloading our entire HTML page!
Single Page Application

• One disadvantage of our site though is that the URL is now less informative.
• You’ll notice in the video above that the URL remains the same even when we switch from
section to section.
• We can solve this problem using the JavaScript History API.
• This API allows us to push information to our browser history and update the URL manually.
Single Page Application

• Let’s take a look at how we can use this API. Imagine we have a Django project identical to the
previous one, but this time we wish to alter our script to employ the history API:
Single Page Application

• before we call the showSection function above, we employ the history.pushState function.
• This function adds a new element to our browsing history based on three arguments:
1. Any data associated with the state.
2. A title parameter ignored by most web browsers
3. What should be displayed in the URL.
Single Page Application

• The other change we make in the above JavaScript is in setting the onpopstate parameter, which
specifies what we should do when the user clicks the back arrow.
• In this case, we want to show the previous section when the button is pressed. Now, the site
looks a little more user-friendly:
Scroll

• In order to update and access the browser history, we used an important JavaScript object
known as the window.
• There are some other properties of the window that we can use to make our sites look nicer:
• window.innerWidth: Width of window in pixels
• window.innerHeight: Height of window in pixels
Scroll

• While the window represents what is currently visible to the user, the document refers to the
entire web page, which is often much larger than the window, forcing the user to scroll up and
down to see the page’s contents.
• To work with our scrolling, we have access to other variables:
• window.scrollY: How many pixels we have scrolled from the top of the page
• document.body.offsetHeight: The height in pixels of the entire document.
Scroll

• We can use these measures to determine whether or not the user has scrolled to the end of a page using the
comparison:
• window.scrollY + window.innerHeight >= document.body.offsetHeight.
• The following page, for example, will change the backgroud color to green when we reach the bottom of a
page:
Scroll – infinite scroll

• Changing the background color at the end of the page probably isn’t all that useful, but we may
want to detect that we’re at the end of the page if we want to implement infinite scroll.
• For example, if you’re on a social media site, you don’t want to have to load all posts at once, you
might want to load the first ten, and then when the user reaches the bottom, load the next
ten.Let’s take a look at a Django application that could do this.
• This app has two paths in urls.py (below) and two corresponding views in views.py (next slide):
Scroll – infinite scroll

• Views.py
Scroll – infinite scroll

• Notice that the posts view requires two arguments: a start point and an end point.
• In this view, we’ve created our own API, which we can test out by visiting
localhost:8000/posts?start=10&end=15
• which returns the following JSON:
Scroll – infinite scroll

• Now, in the index.html template that the site loads, we start out with only an empty div in the
body and some styling.
• Notice that we load our static files at the beginning, and then we reference a JavaScript file within
our static folder.
Scroll – infinite scroll

• Now with JavaScript, we’ll wait until a user scrolls to the end of the page and then load more
posts using our API:
Scroll – infinite scroll

• Now, we’ve created a site with infinite scroll!


Part 2
Animation - CSS

• Another way we can make our sites a bit more interesting is by adding some animation to them. It turns out
that in addition to providing styling, CSS makes it easy for us to animate HTML elements.
• To create an animation in CSS, we use the format below, where the animation specifics can include
starting and ending styles (from and to) or styles at different stages in the duration (anywhere from 0%
to 100%).
• For example:
Animation - CSS

• Then, to apply an animation to an element, we include the animation-name, the animation-duration (in
seconds), and the animation-fill-mode (typically forwards). For example, here’s a page where a title
grows when we first enter the page:
Animation - CSS

• the animation-fill-mode:
• forwards: The element will retain the style values that is set by the last keyframe (depends on
animation-direction and animation-iteration-count)
• backwards: The element will get the style values that is set by the first keyframe (depends on
animation-direction), and retain this during the animation-delay period
Animation - CSS

• We can do more than just manipulate size: the below example shows how we can change the position of
a heading just by changing a few lines:
Animation - CSS

• Now, let’s look at setting some intermediate CSS properties as well. We can specify the style at any
percentage of the way through an animation.
• In the below example we’ll move the title from left to right, and then back to left by altering only the
animation from above
Animation - CSS

• If we want to repeat an animation multiple times, we can change the animation-iteration-count to a


number higher than one (or even infinite for endless animation).
• There are many animation properties that we can set in order to change different aspects of our
animation.
• In addition to CSS, we can use JavaScript to further control our animations.
• Let’s use our moving header example to show how we can create a button that starts and stops the
animation.
Animation - CSS

• Assuming we already have an animation, button, and heading, we can add the following script to start
and pause the animation:
Animation – CSS - Updating Previous Example

• Now, let’s look at how we can apply our new knowledge of animations to the posts page we made earlier.
• Specifically, let’s say we want the ability to hide posts once we’re done reading them.
• Let’s imagine a Django project identical to the one we just created, but with some slightly different HTML
and JavaScript.
• The first change we’ll make is to the add_post function, this time also adding a button to the right side of
the post:
Animation – CSS - Updating Previous Example

• Now, we’ll work on hiding a post when the hide button is clicked.
• To do this, we’ll add an event listener that is triggered whenever a user clicks anywhere on the page.
• We then write a function that takes in the event as an argument, which is useful because we can use the
event.target attribute to access what was clicked on. We can also use the parentElement class to find the
parent of a given element in the DOM.
• element.remove()
Animation – CSS - Updating Previous Example

• We can now see that we’ve implemented the hide button, but it
doesn’t look as nice as it possibly could.
• Maybe we want to have the post fade away and shrink before we
remove it.
• In order to do this, we’ll first create a CSS animation.
• The animation (on the right) will spend 75% of its time changing the
opacity from 1 to 0, which essentially makes the post fade out
slowly. It then spends the rest of the time moving all of its height-
related attributes to 0, effectively shrinking the post to nothing.
Animation – CSS - Updating Previous Example

• As you can see, the hide functionality now looks a lot nicer!
Part 3
React

• At this point, you can imagine how much JavaScript code would have to go into a more complicated
website. We can mitigate how much code we actually need to write by employing a JavaScript
framework, just as we employed Bootstrap as a CSS framework to cut down on the amount of CSS we
actually had to write.
• One of the most popular JavaScript frameworks is a library called React.
• So far in this course, we’ve been using imperative programming methods, where we give the computer a
set of statements to execute.
• For example, to update the counter in an HTML page we might have have code that looks like this:

View Logic
React

• React allows us to use declarative programming, which will allow us to simply write code explaining what
we wish to display and not worry about how we’re displaying it.

• In React, a counter might look a bit more like this:

View Logic
React

• The React framework is built around the idea of components, each of which can have an underlying state.
• A component would be something you can see on a web page like a post or a navigation bar, and a
state is a set of variables associated with that component.
• The beauty of React is that when the state changes, React will automatically change the DOM
accordingly.
React

• There are a number of ways to use React, (including the popular create-react-app command published
by Facebook) but today we’ll focus on getting started directly in an HTML file.
• To do this, we’ll have to import three JavaScript Packages:
1. React: Defines components and their behavior
2. ReactDOM: Takes React components and inserts them into the DOM
3. Babel: Translates from JSX, the language in which we’ll write in React, to plain JavaScript that our
browsers can interpret. JSX is very similar to JavaScript, but with some additional features, including
the ability to represent HTML inside of our code.
React

• Let’s dive in and create our first React application!


React

• Since this is our first React app, let’s take a detailed look at what each part of this code is doing:
• In the three lines above the title, we import the latest versions of React, ReactDOM, and Babel.
• In the body, we include a single div with an id of app. We almost always want to leave this empty, and
fill it in our react code.
• We include a script tag where we specify that type="text/babel". This signals to the browser that
the following script needs to be translated using Babel.
• Next, we create a component called App. Components in React can be represented by JavaScript
functions.
• Our component returns what we would like to render to the DOM. In this case, we simply return
<div>Hello!</div>.
• The last line of our script employs the ReactDOM.render function, which takes two arguments:
1) A component to render
2) An element in the DOM inside of which the component should be rendered
React

• Now that we understand what the code is doing, we can take a look at the resulting webpage:
React

• One useful feature of React is the ability to render components within other components.
• To demonstrate this, let’s create another component called Hello:

• And now, let’s render three Hello components inside of our App component:

This gives us a page that looks like:


React

• So far, the components haven’t been all that interesting, as they are all exactly the same. We can make
these components more flexible by adding additional properties (props in React terms) to them.
• For example, let’s say we wish to say hello to three different people.
• We can provide those people’s names in a method that looks similar to HTML attributes:

• We can then access those props using:


props.PROP_NAME. We can then insert this into
our JSX using curly braces:
React

• Now, let’s see how we can use React to re-implement the counter page we built when first working with
JavaScript.
• Our overall structure will remain the same, but inside of our App component, we’ll use React’s useState
hook to add state to our component.
• useState declares a state variable that you can update directly.
• The argument to useState is the initial value of the state, which we’ll set to 0.
• The function returns both a variable representing the state and a function that allows us to update the
state.
React

• Now, we can work on what the function will render, where we’ll specify a header and a button.
• We’ll also add an event listener for when the button is clicked, which React handles using the onClick
attribute:
React

• Finally, let’s define the updateCount function.


• To do this, we’ll use the setCount function, which can take as argument a new value for the state.

Now we have a functioning counter site!


• Now we have a functioning counter site!
React

• Counter Example Code:


React – Addition Example

• Now that we have a feel for the React framework, let’s work on using what we’ve learned to build a game-
like site where users will solve addition problems.
• We’ll begin by creating a new file with the same setup as our other React pages.
• To start building this application, let’s think about what we might want to keep track of in the state.
• We should include anything that we think might change while a user is on our page.
• Our state might include:
1) num1: The first number to be added
2) num2: The second number to be added
3) response: What the user has typed in
4) score: How many questions the user has answered correctly.
React – Addition Example

• Now, our state can be a JavaScript object that includes all of this information:

• Now, using the values in the state, we can render a basic user interface.
React – Addition Example

• Now, the basic layout of the site looks like this:

• At this point, the user cannot type anything in the input box because its value is fixed as
state.response which is currently the empty string.
• To fix this, let’s add an onChange attribute to the input element, and set it equal to a function called
updateResponse.
React – Addition Example

• Now, we’ll have to define the updateResposne function, which takes in the event that triggered the
function, and sets the response to the current value of the input.
• This function allows the user to type, and stores whatever has been typed in the state.
React – Addition Example

• Now, let’s add the ability for a user to submit a problem.


• We’ll first add another event listener to the input element and link it to a function we’ll write next:

• Next , we’ll define the inputKeyPress function (next slide)


React – Addition Example

• In this function, we’ll first check whether the Enter


key was pressed, and then check to see if the
answer is correct.
• When the user is correct:
• we want to increase the score by 1.
• choose random numbers for the next problem.
• clear the response.
• If the answer is incorrect:
• we want to decrease the score by 1.
• clear the response.

Math.random() returns a random number between 0 (inclusive), and 1


(exclusive):
React – Addition Example

• Finally, let’s add the ability to win the game after gaining 10 points.
• To do this, we’ll add a condition to the render function (App), returning something completely different
once we have 10 points:
React – Addition Example

• We can do more to change the color to red if the answer is wrong, and green if the user wins the game.
• To do this, we will make some changes to the code:
1) We will add a Boolean attribute to the state object.
2) Create two functions.
3) Update the inputKeyPressed Function.
4) Add a condition to the end of App function

1. State Object
{
score: state.score + 1 ,
response:"",
num1: Math.ceil(Math.random() * 10) ,
num2: Math.ceil(Math.random() * 10) ,
incorrect:false
}
React – Addition Example

2. First function
function renderProblem(){
//determine the div class based on the incorrect variable
let divClass="";
if(state.incorrect){
divClass="incorrect";
}
Return ( <div>
<div id="problem" className={divClass}> {state.num1} + {state.num2}
</div>
<input value={state.response} type="text" onChange={updateResponse}
onKeyPress={inputKeyPress} />
<div>Score: {state.score}</div>
</div>);
}

2. Second function
function renderWinScreen(){
return (
<div id="winner">You Won!</div>
);
}
React – Addition Example
3. Set the incorrect value to false when the answer is right, and Value to true in case the answer is wrong
in the inputKeyPress function.

incorrect:false
incorrect:true

4. Update the App function by adding a condition at the end, when the score reach 10 it will return the
Win screen, otherwise it will return the problem.

if(state.score === 10){


return (renderWinScreen());
}else {
return (renderProblem() );
}
React – Addition Example

• To put some finishing touches on the application, let’s add some style to the page.

<style>
#app {
text-align: center;
font-family: sans-serif;
}

#problem {
font-size: 72px;
}

#winner {
font-size: 72px;
color: green;
}
.incorrect {
font-size: 72px;
color: red;
}

</style>
React – Addition Example

• Now, let’s take a look at our application!

You might also like