The Overlapping Rectangles using CSS and Javascript

in #blog4 years ago

[caption id="attachment_46858" align="alignnone" width="325"]Three Divs in HTML/CSS Make three rectangles as shown in the figure. Clicking on any rectangle should alert the name of the rectangle[/caption]

Make three rectangles (Div or Span containers) as shown in the above figure. Clicking on any rectangle should display (using alert is fine) the name of the rectangle.

Three Rectangles in HTML Div Containers


The Three rectangles can be represented using HTML Div containers/elements. The outmost rectangle (also the biggest one) wraps the second biggest and so on.

<div id="Div1">
  <div id="Div2">
    <div id="Div3">
&lt;/div&gt;

</div>
</div>

CSS Styles for the Rectangles


We can use the CSS to control how these rectangles look like e.g. the colour, the size etc.

div {
    border-style: solid;
    border-color: grey;    
    cursor: pointer;
    text-align: center;
}

div#Div1 {
background-color: lightblue;
width: 500px;
height: 400px;
}

div#Div2 {
background-color: orange;
width: 400px;
height: 300px;
margin: 50px;
}

div#Div3 {
background-color: transparent;
width: 300px;
height: 200px;
margin: 50px;
}

Clickable Rectangles in Javascript


Finally, we can use Javascript to define the clicking behaivor. We can define each Div's onclick event but that is not an elegant solution as there will be duplicate code and you have to manually associate the behavior for each rectangle by ID explicitly.

const divs = document.querySelectorAll("div");
for (let i = 0; i < divs.length; ++ i) {
    divs[i].addEventListener('click', function(i) {
        alert(divs[i].id);
        // avoid fired more than once for overlapping area
        event.stopPropagation();        
    }.bind(this, i));
}

The above Javascript will query all the Divs and add event listner (click) to each of them. Remember to call event.stopPropagation to avoid firing multiple events on the overlapping area.

Want to see how the above combines and works together in the JS playground?: https://jsfiddle.net/9mpjegL8/

--EOF (The Ultimate Computing & Technology Blog) --

Reposted from: https://helloacm.com/the-overlapping-rectangles-using-css-and-javascript/

Coin Marketplace

STEEM 0.13
TRX 0.34
JST 0.036
BTC 109207.95
ETH 4399.20
USDT 1.00
SBD 0.84