0% found this document useful (0 votes)
15 views

JavaScript + CSS M3L2

Основы Фронтенд. Лекция2

Uploaded by

uxdesigner.tsoi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

JavaScript + CSS M3L2

Основы Фронтенд. Лекция2

Uploaded by

uxdesigner.tsoi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

MODULE 3.

LESSON 2

Functions and events


in JavaScript

Methodological
Скачать Guidelines
методичку
MODULE 3. LESSON 2

New topic:
Timers and Functions
Timer
We found out that it's possible to delay code execution for some
time. What data might the browser need to do that?
Timer
We found out that it's possible to delay code execution for some
time. What data might the browser need to do that?

1. The time by which the code execution should be delayed.


Timer
We found out that it's possible to delay code execution for some
time. What data might the browser need to do that?

1. The time by which the code execution should be delayed.


2. The code itself.
Timer
We found out that it's possible to delay code execution for some
time. What data might the browser need to do that?

1. The time by which the code execution should be delayed.


2. The code itself.

Well, how do we program all that?


setTimeout()
To execute the code with a delay, the setTimeout() command is
used. As additional parameters, you must specify a set of
commands to delay and the number of milliseconds to delay
code execution.
setTimeout()
To execute the code with a delay, the setTimeout() command is
used. As additional parameters, you must specify a set of
commands to delay and the number of milliseconds to delay
code execution.

Like this:

setTimeout(<command set>, <time>)


setTimeout()
To execute the code with a delay, the setTimeout() command is
used. As additional parameters, you must specify a set of
commands to delay
and the number of milliseconds to delay code execution.

Like this:

setTimeout(<command set>, <time>)

And how to combine commands into a set?


setTimeout()
The fact is that you cannot pass commands directly to
setTimeout(). For example, if you try to delay the output of text
to the console as follows:

setTimeout(console.log('Hello, Algorithmics!'), 500)

we won't get exactly what we expect :(


Functions
To combine commands into a whole,
programming use functions.

A function is a named block of code that can be called an


infinite number of times once it is created.

We have already encountered functions. Can you give


examples?
Functions
A function is a named block of code that can be called an
infinite number of times once it is created.

1. alert().
2. console.log().
3. querySelector().

In the last lesson, we learned to use these functions without


thinking about what's going on behind the scenes.
Functions
There is a code behind every function we use,
and the name of the function is a link to this code. The code is
triggered only at the moment when the function is called by
name.

After all, JavaScript won't start looking for an object on the page
and editing it if we don't call the function we need, right?

And if we call it, a tree search will start.


Functions

function querySelector(selector){
// go over the tree
// select an element
// return the element
}

Saving the result Calling a


function

let main_section = document.querySelector('.content')


Functions
You can also create your own functions in JavaScript. It can be
any set of commands, the main thing is to write everything
correctly.

To create a full-fledged function, you need to:


Functions
You can also create your own functions in JavaScript. It can be
any set of commands, the main thing is to write everything
correctly.

To create a full-fledged function, you need to:


● declare the function;
● write the function body.
Functions
Let's start with the function declaration. To do this, you need
to use a keyword and come up with a name.
Functions
Let's start with the function declaration. To do this, you need
to use a keyword and come up with a name. Like this:

function summa () We will need brackets later,


but we still have to put them
in code
Key Name
word
Functions
Now let's move on to the function body. Let our function
calculate the sum of two numbers and output the result to the
console:

let number1 = 5
let number2 = 10
let result = number1 + number2
console.log(result)
Functions
Connecting the function declaration and its body:

function summa() {
let number1 = 5
let number2 = 10
let result = number1 + number2
console.log(result)
}
Functions
Connecting the function declaration and its body:

Curly braces restrict


function summa() {
the function body.
let number1 = 5
let number2 = 10
let result = number1 + number2
console.log(result)
}
Functions
Connecting the function declaration and its body:

function summa() {
Done :)
let number1 = 5
let number2 = 10
let result = number1 + number2
console.log(result)
}
Functions
Now if you call the function by its name:

summa()
the result of adding two numbers will be output to the console.
But there is a flaw: the function code displays the sum of two
exact numbers: 5 and 10. This means that when the function is
called, the number 15 will always be displayed in the console.

How do we make the function universal?


Functions
Functions can accept data as input. For example, the
querySelector() command takes a selector in the form of a
string as input:

document.querySelector(<selector>)

And uses it to do a search through the tree.

Perhaps this should be provided for?


Functions
When declaring a function, we can provide the ability to receive
data when the function is called.
Functions
When declaring a function, we can provide the ability to receive
data when the function is called. Take a look
at the code:

function summa(number1, number2) {


let result = number1 + number2
console.log(result)
}
summa(2, 3)
Functions
When declaring a function, we can provide the ability to receive
data when the function is called. Take a look
at the code:

function summa(number1, number2) {


let result = number1 + number2
console.log(result)
}
summa(2, 3)
What will be output to the console?
Functions
The function arguments are specified in parentheses. The
argument values are passed to the function when it is called.
Within the function, arguments can be used as variables.

function summa( number1 , number2 ) {


...
}
summa( 2 , 3 )
Functions
You can program the function so that it returns a value. Now
we can do the following with the help of functions:
● output the result to the console;
● make changes to a page.

Then how do we get a value to use in the


code?
Functions
Let's go back to the function for calculating the sum:
function summa(number1, number2) {
let result = number1 + number2
console.log(result)
}
summa(2, 3)

The result is output to


the console.
Functions
Instead of console.log(), let's write return:
function summa(number1, number2) {
let result = number1 + number2
return result
}
summa(2, 3)

The result is returned to


the program.
Functions
In this case, the result can be saved to a variable:
function summa(number1, number2) {
let result = number1 + number2
return result
}
let sum = summa(2, 3)

After the function is called, the value it


returns will be put into a variable.
setTimeout()
Let's go back to the setTimeout() function:

setTimeout(<command set>, <time>)


Now we know how to create a set of commands and we can
fully use this tool!
Task
The Galaxy project, which aims to organize flights to Mars, is
pleased to remind users of a 20 percent discount on tickets. We
need to do this 2 minutes after the user has opened the page.

What steps will we take?


Task
The Galaxy project, which aims to organize flights to Mars, is
pleased to remind users of a 20 percent discount on tickets We
need to do this 2 minutes after the user has opened the page.

1. We create a function that calls a pop-up window.


Task
The Galaxy project, which aims to organize flights to Mars, is
pleased to remind users of a 20 percent discount on tickets. We
need to do this 2 minutes after the user has opened the page.

1. We create a function that calls a pop-up window.


2. We use setTimeout() for delayed code execution.
Task
Let's write a function:

function remind() {
alert('20% discount on one-way ticket!')
}
Task
Adding setTimeout():

function remind() {
alert('20% discount on one-way ticket!')
}
setTimeout(remind, 2*60*1000)
Task
Detail

function remind() {
alert('20% discount on one-way ticket!')
}
setTimeout( remind , 2*60*1000)

setTimeout() only accepts the function name


as input, so we can write it without
parentheses at the end.
Task
function remind() {
alert('20% discount on one-way ticket!')
}
setTimeout(remind, 2*60*1000)

We did it!
Task
The text of the notification may be different each time. How can
this be programmed?
Task
The text of the notification may be different each time. How can
this be programmed?
You can write a function so that it accepts a message as an
argument:

function remind(message) {
alert(message)
}
setTimeout(remind, 2*60*1000)
Task
The text of the notification may be different each time. How can
this be programmed?
You can write a function so that it accepts a message as an
argument:

function remind(message) { What should we do


alert(message) then?
}
setTimeout( remind , 2*60*1000)
Task
The text of the notification may be different each time. How can
this be programmed?
You can write a function so that it accepts a message as an
argument:
If you do this, the
remind function will be
function remind(message) { executed immediately.
alert(message)
}
setTimeout(remind('Message'), 2*60*1000 )
Anonymous functions
In such cases, anonymous functions are used. They don't
need to come up with a name because the whole construct is
passed to setTimeout:

function remind(message) {
alert(message)
}
setTimeout(function(){remind('Message') }, 2*60*1000)
Anonymous functions
In such cases, anonymous functions are used. They don't
need to come up with a name because the whole construct is
passed to setTimeout:
We pass the function
that will be called
at the right moment.
function remind(message) {
alert(message)
}
setTimeout( function(){remind('Message') }, 2*60*1000)
Anonymous functions
In such cases, anonymous functions are used. They don't
need to come up with a name because the whole structure is
passed to setTimeout:
And then the remind function
will be called from it
with the argument passed.
function remind(message) {
alert(message)
}
setTimeout( function(){remind('Message') }, 2*60*1000)
Bonus
Interesting facts about the setTimeout() command. What do you
think, which of the two functions will be executed first?

function first() {
console.log('The first function')
}

function second() {
console.log('The second function')
}

setTimeout(first, 50000)
setTimeout(second, 100)
Bonus
The second function will be executed first.

Functions are executed not sequentially but in parallel. Setting


the timer doesn't make the JS wait all 50 seconds
and then move on to the rest of the code, so both timers start
almost simultaneously.
To summarize:
1. What is a function?
2. Is it possible to create a function yourself?
3. How many times can a function be called?
4. In what form should the delay time be passed to
setTimeout()?
5. What keyword is used to return a value from a function?
Remember I told
you about the new
order coming in?

Well, this is the


Galaxy company
and they're
sending people to
Mars!!!

We will help them


with their website.
Are you ready?

10:2
1
MODULE 3. LESSON 1

New topic.
Event handling
Discussion
Let's look at this page again:
Discussion
Let's formulate what's happening:
1. There is a button on the page.
2. The user clicks on the button.
3. Page styles change.

In another way, the second point can be written as…


Discussion
Let's formulate what's happening:
1. There is a button on the page.
2. The user clicks on the button.
3. Page styles change.

In another way, the second point can be written as:

An event occurs on the page


Event is
a browser signal that the user has performed an action on the
page Here is a list of the main actions that the browser can
recognize:
● click ― clicking on an element
● mouseenter ― moving the mouse to a block
● mouseleave ― moving the mouse outside a block
● mousemove ― mouse movement
Event handling
In JavaScript, such signals can be intercepted and certain
actions can be performed at the moment they occur. Such a
reaction is called event handling.
Event handling
In JavaScript, such signals can be intercepted and certain
actions can be performed at the moment they occur. Such a
reaction is called event handling.
To do this, JS uses the addEventListener() command. . This is
the way to intercept the signal, to subscribe to the block.
Event handling
In JavaScript, such signals can be intercepted and certain
actions can be performed at the moment they occur. Such a
reaction is called event handling.
To do this, JS uses the addEventListener() command. . This is
the way to intercept the signal, to subscribe to the block. Like
this:
<object>.addEventListener(<event name>, <function>)
Event handling

<object> .addEventListener(<event name>, <function>)

An event can be expected for a certain element


from the page. Then you can refer to the object obtained using
querySelector.
If the event should be handled within the entire page, you can
refer to the document object.
Task
The Galaxy project needs help again. This time you need to
change the picture on the background when the button is being
clicked:
Event handling
Here is the HTML code. It's worth remembering the necessary
selectors:

<div class="btn-change-img">Switch theme</div>


<header>
<h1>Let's fly to Mars!</h1>
</header>
Event handling
Let's discuss the sequence of actions:
Event handling
Let's discuss the sequence of actions:
1. Write a function to change the background.
Event handling
Let's discuss the sequence of actions:
1. Write a function to change the background.
2. Subscribe to updates of the button object.
Event handling
Let's discuss the sequence of actions:
1. Write a function to change the background.
2. Subscribe to updates of the button object.
3. Specify what event we will respond to and how.

Let's go!!
Event handling
Let's start with creating a function. What properties should we
change?
Event handling
Let's start with creating a function:

function switchTheme() {
let header = document.querySelector( 'header')

header.style.background = 'url(dark4.jpg)'
header.style.backgroundSize = 'cover'
}
Event handling
Now let's get to the button:

function switchTheme() {
let header = document.querySelector( 'header')

header.style.background = 'url(dark4.jpg)'
header.style.backgroundSize = 'cover'
}
let btn = document.querySelector('.btn-change-img')
Event handling
The last step is to program the response:

function switchTheme() {
let header = document.querySelector( 'header')

header.style.background = 'url(dark4.jpg)'
header.style.backgroundSize = 'cover'
}
let btn = document.querySelector('.btn-change-img')
btn.addEventListener('click', switchTheme)
Event handling
Considering the last line:

btn . addEventListener ( 'click' , switchTheme )


Event handling
Let's take a closer look at the last line:

Referring to
the button

btn . addEventListener ( 'click' , switchTheme )


Event handling
Let's take a closer look at the last line:

Referring to
the button

btn . addEventListener ( 'click' , switchTheme )


Subscribing to
events
Event handling
Let's take a closer look at the last line:

Referring to Specifying the desired


the button event as a string

btn . addEventListener ( 'click' , switchTheme )


Subscribing to
events
Event handling
Let's take a closer look at the last line:

Referring to Specifying the desired


the button event as a string

btn . addEventListener ( 'click' , switchTheme )


Subscribing to Specifying the
events function name
Event handling
Let's remember about the other events:
● click ― clicking on an element
● mouseover ― moving the mouse to a block
● mouseout ― moving the mouse outside a block
● mousemove ― mouse movement
mouseover and mouseout
Task: to refine the buttons in the flight
request form so that they become
transparent when the mouse is
hovered over them, and regain their
background when the mouse is
moved out of the button.
This is already implemented for one of
the buttons. Let's do it for the second
one, shall we?
mouseover and mouseout
HTML code:

<div class="submit-btn-row">
<div class="submit-btn submit-btn-calc">
Price
</div>
<div class="submit-btn submit-btn-send">
Send
</div>
</div>
mouseover and mouseout
The sequence of actions will be the same as for handling the click
event: we write a function, get a button, and add event handling.
The only difference is the event to respond to:

function make_transparent() {
send_btn.style.backgroundColor = 'transparent'
}
letsend_btn = document.querySelector('.submit-btn-send')
send_btn.addEventListener('mouseover', make_transparent)
mouseover and mouseout
function make_transparent() {
send_btn.style.backgroundColor = 'transparent'
}
letsend_btn = document.querySelector('.submit-btn-send')
send_btn.addEventListener( 'mouseover' , make_transparent)

It will trigger when the


cursor moves to the
object.
mouseover and mouseout
Let's repeat the same for mouseout:

function make_colorful() {
send_btn.style.backgroundColor = '#C2AB99'
}
letsend_btn = document.querySelector('.submit-btn-send')
send_btn.addEventListener( 'mouseout' , make_colorful)

It will trigger when the


cursor moves outs of the
object.
mouseover and mouseout
As a result, we'll get this code:
function make_transparent() {
send_btn.style.backgroundColor = 'transparent'
}

function make_colorful() {
send_btn.style.backgroundColor = '#C2AB99'
}

let send_btn = document.querySelector('.submit-btn-send')

send_btn.addEventListener('mouseover', make_transparent)
send_btn.addEventListener('mouseout', make_colorful)
mouseover and mouseout
And a wonderful result!
Event handling
The last one left!
● click ― clicking on an element
● mouseover ― moving the mouse to a block
● mouseout ― moving the mouse outside a block
● mousemove ― mouse movement
mousemove
The mousemove event is triggered if the user moves the cursor
within a page or block. The only difference is that this event is
almost always triggered because the cursor is almost always in
motion.
This event will be triggered regularly, with a frequency
determined by the browser.
mousemove

The teacher will show you an example of handling


such an event.
Event handling
It seems that the events are over!
● click ― clicking on an element
● mouseover ― moving the mouse to a block
● mouseout ― moving the mouse outside a block
● mousemove ― mouse movement
Сonsolidating the material

● What events do you remember?


● Which object should be referred to in order to track an event
throughout the page?
● What command allows monitoring events within an object?

You might also like