Click to arrange box on top of another using javascript

<style>
	.boxz {position: absolute; width: 400px; height: 300px; background-color: rgba(38,9,221,0.31); z-index: 501;}

</style>
<div id="zcount">501</div>
<div onclick="bringtofront(event);" class="boxz"></div><br>
<div onclick="bringtofront(event);" class="boxz"></div><br>
<div onclick="bringtofront(event);" class="boxz"></div><br>
<div onclick="bringtofront(event);" class="boxz"></div><br>
<div onclick="bringtofront(event);" class="boxz"></div><br>

<script>
function bringtofront(event) {
	var zcount = document.getElementById('zcount').innerHTML; 
	document.getElementsByClassName('boxz').style.zIndex = zcount;
	document.getElementsByClassName('boxz').style.backgroundColor = 'red';
	var zcount = document.getElementById('zcount').innerHTML = zcount + 1;
};
</script>

The box clicked on should turn red and sit on top of all other boxes

You could do something like this.

HTML

<div id="boxes">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>   
</div>

JS

window.addEventListener('DOMContentLoaded', () => {
    const boxes = document.querySelector('#boxes');
    let lastSelected = null;

    // add the click eventlistener to the container #boxes
    boxes.addEventListener('click', ({target}) => {
        // If the element clicked on doesn't
        // match a class of .box then exit.
        if (!target.matches('.box')) return;

        // if lastSelected has been set to an element
        // then removed the .selected class
        if (lastSelected) {
            lastSelected.classList.remove('selected');
        }

        // add the .selected class to the currently clicked element
        target.classList.add('selected');    
        // set lastSelected to this element, ready for the next click
        lastSelected = target;
    })    
})

Then have a css declaration for .selected

.box.selected {
    background-color: red;
    z-index: 999;
}

Something along these lines :slight_smile:

2 Likes
const boxes = document.querySelector('#boxes');
    let lastSelected = boxes;
    ...
    lastSelected.classList.remove('selected');

(Save yourself the if - initialize to an innocuous element. classList.remove doesnt care if the class isnt present.)

The if condition was their to check if lastSelected was null. I see you have changed it’s initial value from null to boxes. No biggy either way, I would say.

I agree it’s not a big thing (certainly not at this scale), but it’s one more line of execution in each evaluation of the function, that only needs to occur once (if null). Every time after the first, the if has to be evaluated unnecessarily shrug

2 Likes