I want to create slider in js. Here is my code. The problem is how I've mentioned, with creating new img
element in new div
element in new header
element "in the same time", sth. like header > div > img
.
const myRequest = new Request('./database.json');
const myHeader = document.querySelector('main');
export const headerTwo = (fragment) => {
fetch(myRequest)
.then(function (response) {
console.warn(response);
return response.json();
})
.then(function () {
let header = document.createElement('div');
// above is the problem with creating header > div > img
header.setAttribute('class', 'slider');
const slideList = [{
img: "https://",
text: 'sth 1'},{
img: "https://",
text: 'sth 2'},{
img: "https://",
text: 'sth 3'}
];
const time = 3000;
let active = 0;
const changeSlide = () => {
active++;
if (active === slideList.length) {
active = 0;
}
header.src = slideList[active].img;
header.textContent = slideList[active].text;
};
let indexInterval = setInterval(changeSlide, time);
myHeader.appendChild(header);
})
.then(function() {
console.log('Co to ????');
})
.catch(function (error) {
console.log('--------- ', error);
});
}
That code should do it
let header = document.createElement('header')
let div = document.createElement('div')
let img = document.createElement('img')
img.setAttribute('src','') // set value
div.appendChild(img)
header.appendChild(div)
Then append header wherever you need it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.