I'm trying to have my 3 elements marginLeft
differ from each other, with each following one being bigger by 300px
than the previous. Clearly, the 'px' making it a string is in the way, but I don't know how to overcome it.
function render() {
var gElOptions = document.querySelector('.options');
for (var i = 0; i < 3; i ) {
var elOptionBtn = document.createElement('button');
gElOptions.appendChild(elOptionBtn);
elOptionBtn.setAttribute('class', `option-${i}`);
var elOption = document.querySelector(`.option-${i}`);
elOption.style.marginLeft = 1000 'px';
// The problematic line:
if (elOption.style.marginLeft === 1000 'px') elOption.style.marginLeft -= 300 'px';
}
}
<body onload="render()">
<div class="options">
</div>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
function render() {
var gElOptions = document.querySelector('.options');
for (var i = 0; i < 3; i ) {
var elOptionBtn = document.createElement('button');
elOptionBtn.innerHTML = i
gElOptions.appendChild(elOptionBtn);
elOptionBtn.setAttribute('class', `option-${i}`);
//var elOption = document.querySelector(`.option-${i}`);
elOptionBtn.style.marginLeft = i*300 'px';
// The problematic line:
//if (elOption.style.marginLeft === 1000 'px') elOption.style.marginLeft -= 300 'px';
}
}
render()
<div class="options"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Js is only for dynamic adding buttons. (arrow right, arrow left).
Margin for each button is set in css.
const container = document.querySelector('div');
const addButton = () => {
const button = document.createElement('button');
button.textContent = "test"
container.appendChild(button);
}
const delButton = () => {
container.lastChild?.remove()
}
window.addEventListener("keydown", ({key}) => {
switch(key){
case "ArrowLeft": {
delButton();
break;
}
case "ArrowRight": {
addButton();
}
}
})
button{
margin-left: 5px;
}
button:nth-child(1){
margin-left: 10px;
}
button:nth-child(2){
margin-left: 20px;
}
button:nth-child(3){
margin-left: 30px;
}
button:nth-child(4){
margin-left: 40px;
}
button:nth-child(5){
margin-left: 50px;
}
button:nth-child(6){
margin-left: 50px;
}
<div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>