Skip to content
Advertisement

Show div in a row just below clicked button [closed]

So I have a lot of buttons. I used flex-box.

The tricky part is that I don’t know how to place that green block just after the button on a new row. Button with green color means that I clicked on it.

I thought about doing this: we can somehow track the last element in a row(where the button is clicked) and then add a new element with a width of 100% so that it will be on a new line just after the button.

The click will be done using jquery.

I don’t have the code for you to share BUT I actually don’t need you to write the code, the explanation of how I can do it will be enough. Thanks.

enter image description here

Advertisement

Answer

You somehow need to know in which row does the clicked button belongs.

One way is to get the .offsetTop of clicked button. Then, loop through each button until you reach a button with bigger .offsetTop value (this means that the button is in a new row). When you find it, insert your block before this button.

$('.btn').click((e) => {
    let offsetTop = e.target.offsetTop;
    let buttons = $('.btn');
    for (let i=0; i<buttons.length; i++) {
        if (buttons[i].offsetTop > offsetTop) {
            $('.insert').insertBefore(buttons[i]);
            return;
        }
    }
    //clicked button was in last row
    $('.insert').insertAfter(buttons[buttons.length - 1]);
})

Here is a working fiddle: https://jsfiddle.net/mxrw1ofL/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement