I don't know how to write a simple event listener to delete 5% od elements width every time the button is clicked. From 100% to 0%.
substracktBtn.addEventListener('click', function(){
container.style.width = "calc(" + container.style.width + " - 5%)";
})
In this code i got no errors but the div's width is still 100% after the clicks.
This is your solution:
const container = document.querySelector('div')
const button = document.querySelector('button')
const subtractPerClick = container.offsetWidth * 0.05
button.addEventListener('click', () => {
if (container.offsetWidth - subtractPerClick > 0)
container.style.width = container.offsetWidth - subtractPerClick + 'px'
else
container.style.width = '0px'
})
div {
height: 100px;
width: 300px;
background-color: darkblue;
}
<div></div>
<button>Substract</button>
For removing 5% of the current width. This converges!
const container = document.getElementById('container');
const button = document.getElementById('button');
button.addEventListener('click', () => {
container.style.width = container.offsetWidth * 0.95 + 'px'
})
#container {
background-color: red;
width: 200px;
height: 100px;
}
<div id="container"></div>
<button id="button">Substract</button>
For removing 5% of the starting width
const container = document.getElementById('container');
const button = document.getElementById('button');
let startWidth5Percent = container.offsetWidth * 0.05;
button.addEventListener('click', () => {
container.style.width = container.offsetWidth - startWidth5Percent + 'px';
})
#container {
background-color: red;
width: 200px;
height: 100px;
}
<div id="container"></div>
<button id="button">Substract</button>
How about just:
substracktBtn.addEventListener('click', function(){
container.offsetWidth = container.offsetWidth * 0.95
});
Note: untested, not sure if JS requires the 'px' added at the end, but you get the gist.