My coding challenge involves dynamically creating nested <div>
elements within another <div>
when a button is clicked. Upon clicking the button, a new inner <div>
with a unique id is generated inside the outer <div>
, each possessing a random CSS margin-top
value. Although this functionality is functional, my goal now is to constrain the scrolling of the outer <div>
to horizontal movements only. To achieve this, all inner <div>
elements need to be created inline. Unfortunately, using display:inline-block
for the inner <div>
blocks impedes the random margin-top
feature.
(Kudos to user totymedli for the coding assistance)
HTML
<button id="button1">Add box</button>
<div id="outer"></div>
CSS
#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}
.box{
float:left;
width:48px;
height:48px;
background-color:#000;
margin-left:5px;
}
Javascript
var number = 0;
document.getElementById("button1").addEventListener("click", pressButton, false);
function pressButton() {
++number;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(innerDiv);
innerDiv.className += " box";
innerDiv.setAttribute("id", "innerDiv" + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
Test out the live Demo.
In the demo, you'll observe that the creation of new inner <div>
elements is functioning smoothly with varying margin-top
values. How can I enforce horizontal scrolling on the outer <div>
while preventing the inner <div>
from wrapping onto the next line?