the same code from lesson 1
click Edit source(pencil icon), paste the code below into editor field, click Save changes(check mark icon)
1.js - there is the class Olympics24 with methods and properties. To use a class - functions will be methods, global variabless will be properties(+here wll be used constructor). 2.Bind methods and properties using the this pointer getData() { ... .then(data => { console.log(data); this.arrayImages = data; //this this.createContent(this.arrayImages[0]); //this + this }); } changeImageRight() { this.i++; //this if (this.i == this.arrayImages.length) { //this + this this.i = 0; //this } this.setData(this.i); //this + this } changeImageLeft() { this.i--; //this if (this.i == -1) { //this this.i = this.arrayImages.length - 1; //this + this } this.setData(this.i); //this + this } setData(index) { //this document.querySelector('img').setAttribute('src', this.arrayImages[index].file); //this document.querySelector('.title').innerText = this.arrayImages[index].title; } 3.Add outside the class - creating object from class + call getData method //creating an object from the class let olympics24 = new Olympics24; //calling the start method from the class(using the object name) olympics24.getData(); 4.Call methods of object in events //events will be use the object name for call functions from the class document.querySelector('.arrow.right').addEventListener('click', () => { olympics24.changeImageRight(); }); document.querySelector('.arrow.left').addEventListener('click', () => { olympics24.changeImageLeft(); });
document.querySelector('.arrow.right').addEventListener('click', () => {
olympics24.changeImageRight();
});
document.querySelector('.arrow.left').addEventListener('click', () => {
olympics24.changeImageLeft();
});
class Olympics24 {
constructor() {
this.arrayImages = [];
this.i = 0;
}
getData() {
fetch("https://olympics24.25one.com.ua/index.php")
.then(responce => {
return responce.json();
})
.then(data => {
console.log(data);
this.arrayImages = data;
this.createContent(this.arrayImages[0]);
});
}
createContent(dataStart) {
let contentContainer = document.querySelector('.wrap');
let elementImg = document.createElement('img');
elementImg.setAttribute('src', dataStart.file);
contentContainer.appendChild(elementImg);
let elementDiv = document.createElement('div');
elementDiv.setAttribute('class', 'title');
elementDiv.innerText = dataStart.title;
contentContainer.appendChild(elementDiv);
}
changeImageRight() {
this.i++;
if (this.i == this.arrayImages.length) {
this.i = 0;
}
this.setData(this.i);
}
changeImageLeft() {
this.i--;
if (this.i == -1) {
this.i = this.arrayImages.length - 1;
}
this.setData(this.i);
}
setData(index) {
document.querySelector('img').setAttribute('src', this.arrayImages[index].file);
document.querySelector('.title').innerText = this.arrayImages[index].title;
}
}
let olympics24 = new Olympics24;
olympics24.getData();
download the ready code