Let's say I got three buttons and four iframes where the purpose of the button is to control the iframe width. Each iframe will have the same class .resize
since the function they need is the same, so I just use querySelector
to target them.
What's the best way to do this where the button only affects the respective iframe? I have thought of just creating as many classes as possible to different iframe and the function will be the same. But clearly, this will not make sense if I got 100 iframes then I will need to make 100 classes and 100 identical functions.
document.querySelector('.container').addEventListener('click', (e) => {
if (!e.target.matches('button')) return;
const wasChange = e.target.matches(':first-child');
const styles = ['90px', '60%', '100%'].indexOf(e.target);
iframe.style.width = styles[index];
});
.container {
display: grid;
grid-template-columns: repeat(2, minmax(150px, 1fr));
grid-column-gap: 15px;
grid-row-gap: 15px;
}
#iframe01 {
background-color: orange;
}
#iframe02 {
background-color: blue;
}
#iframe03 {
background-color: green;
}
#iframe04 {
background-color: yellow;
}
<div class="container">
<div>
<div>
<button>Small</button>
<button>Medium</button>
<button>Big</button>
</div>
<iframe id="iframe01"></iframe>
</div>
<div>
<div>
<button>Small</button>
<button>Medium</button>
<button>Big</button>
</div>
<iframe id="iframe02"></iframe>
</div>
<div>
<div>
<button>Small</button>
<button>Medium</button>
<button>Big</button>
</div>
<iframe id="iframe03"></iframe>
</div>
<div>
<div>
<button>Small</button>
<button>Medium</button>
<button>Big</button>
</div>
<iframe id="iframe04"></iframe>
</div>
</div>