grect_align
pebble grect_align
by Barry Carter
HTML
<button id="btn">Next</button>
<div id="banner-message">
<div id="test1"></div>
<div id="test"></div>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
height: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#test, #test1 {
position: absolute;
background-color: blue;
width: 350px;
height: 350px;
opacity: 50%;
}
#test1 {
background-color: red;
}
JavaScript
var i = 0;
// find elements
var rect = $("#test");
var rect1 = $("#test1");
var inside_rect = $("#banner-message");
var sw = "350px";
var sh = "150px";
// handle click and add class
$("#btn").on("click", function(){
//$("#test").css({top: 0});
testf(i++);
})
var testf = function(t)
{
var p = rect.position();
var ip = inside_rect.offset();
var x,y;
rect.width(sw);
rect1.width(sw);
rect.height(sh);
rect1.height(sh);
switch(t) {
case 1:
case 4:
case 7:
x = 0;
break;
case 2:
case 5:
case 8:
x = inside_rect.width() - rect.width();
break;
case 0:
case 3:
case 6:
x = (inside_rect.width() - rect.width()) / 2;
break;
}
switch(t) {
case 0:
case 1:
case 2:
y = inside_rect.height() - rect.height();
break;
case 3:
case 4:
case 5:
y = (inside_rect.height() - rect.height()) / 2;
break;
case 6:
case 7:
case 8:
y = 0
break;
}
var px = x; var py = y;
var clip = true;
if (clip) {
if (x < 0) {
rect.width(rect.width() - x);
x = 0;
}
if (x + rect.width() > inside_rect.width()) {
var ad = (x + rect.width()) - inside_rect.width();
rect.width(rect.width() - ad);
}
if (y < 0) {
rect.height(rect.height() - y);
y = 0;
}
if (y + rect.height() > inside_rect.height()) {
var cd = (y + rect.height()) - inside_rect.height();
rect.height(rect.height() - cd);
}
}
rect1.css({left: ip.left + px, top: ip.top + py, position: "absolute"});
x = ip.left + x;
y = ip.top + y;
rect.css({left: x, top: y, position: "absolute"});
if (i > 8)
i = 0;
}