1
I have a slide where the button should always be positioned according to a given image. When resizing the screen the position of the image is changed causing the button to be misaligned and it is necessary to refresh the page to return to the correct position, I tried to use a resize
however the update of the button referring to the image does not occur, if someone can guide me the solution would be grateful.
/* Slide */
const btnPrevious = document.querySelector('#previous');
const btnNext = document.querySelector('#next');
const users = document.querySelectorAll('.user');
const screenWidth = document.querySelector('.container').clientWidth;
const arrUsers = Array.prototype.slice.call(users);
let currentUser = 0;
/* Quote */
const quoteTop = document.querySelector('.quote').getBoundingClientRect().top;
const quoteLeft = document.querySelector('.quote').getBoundingClientRect().left;
const imgQuote = document.querySelector('.imgQuote');
/* Buttons */
const buttons = document.querySelector('.buttons');
const image = document.querySelector('.imgUser');
const buttonsHeight = buttons.offsetHeight;
const buttonsWidth = buttons.offsetWidth;
const positionXBtn = image.getBoundingClientRect().left;
const positionYBtn = image.getBoundingClientRect().bottom;
/* Behavior's slide */
function addClass(index) {
users[index].classList.add('active');
}
function changeClass() {
arrUsers.forEach((element) => {
element.classList.remove('active');
addClass(currentUser);
});
}
function handleClick(event) {
if (event.target.id === 'next' && currentUser < users.length - 1) {
currentUser += 1;
changeClass();
}
if (event.target.id === 'previous' && currentUser > 0) {
currentUser -= 1;
changeClass();
}
}
btnPrevious.addEventListener('click', handleClick);
btnNext.addEventListener('click', handleClick);
/* button position */
function btnAppear() {
buttons.style.top = `${positionYBtn - buttonsHeight / 2}px`;
if (screenWidth > 1024) {
buttons.style.left = `${positionXBtn + 45}px`;
imgQuote.style.top = `${quoteTop - 65}px`;
imgQuote.style.left = `${quoteLeft + 125}px`;
} else {
buttons.style.left = `${screenWidth / 2 - buttonsWidth / 2}px`;
imgQuote.style.top = `${quoteTop - 23}px`;
}
}
btnAppear();
window.addEventListener('resize', btnAppear);
Unfortunately it didn’t work, I tried to switch to window.onresize but it didn’t work either. I used a console.log to test and the event is triggered when the screen resize happens, but the style of the element is not changed.
– Alexandre
Try to see if your script tag is on top of the body, if you’re on the bottom of the body tag
– NoFace