Daniel Ramirez-Escudero Daniel Ramirez-Escudero -5 years ago 120
Javascript Question

How to create dynamic diagonal line from left-bottom to right-top corner?

I've created a simple layout where I have three divs which interact. One is the logo in the middle of the screen and the other are two blocks which with jQuery are moved out of the screen. I used the

option from CSS to apply a degree transformation. I would like to apply the certain degree depending on the screen, so this degree will apply to all screens correctly.

Visual example: http://jsfiddle.net/6a93T/1/

For now I have this code:


<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/jq.animation.js"></script>
<div id="preloader">
<div id="blocktop"></div>
<div id="logo"></div>
<div id="loadline"></div>
<div id="blockbottom"></div>


overflow: hidden;

width: 100%;
height: 100%;

background-image: url('../img/logotest.png');
width: 300px;
height: 300px;
display: block;
position: fixed;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -150px;
z-index: 1000;

background-color: #fff4ed;
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: -50%;
z-index: 10;

transform: skew(-45deg);
-o-transform: skew(-45deg);
-moz-transform: skew(-45deg);
-webkit-transform: skew(-45deg);

background-color: #ff7f33;
width: 100%;
height: 100%;
position: absolute;
bottom: 0px;
right: -50%;

transform: skew(-45deg);
-o-transform: skew(-45deg);
-moz-transform: skew(-45deg);
-webkit-transform: skew(-45deg);




/*$("button").click(function() */

left: '-120%',
opacity: '0'},

right: '-120%',
opacity: '0'},



Answer Source

Use trigonometry to compute the desired angle:

var angle = Math.atan2($(window).width(),$(window).height()); // in radians

(Note for math geeks and other pedants: the arctangent would normally take the height divided by the width, not the other way around. In this case, however, we're skewing a vertical line instead of a horizontal one, so the above code gives the desired result.)

Note that newer versions of jQuery will automatically add the necessary -webkit- or -moz- prefix to that CSS transform property.

You might also want to display:none the elements until the above code can alter the angle, and then show() them immediately after the angle is computed:

$('#blocktop,#blockbottom').css('transform', 'skew(-' + angle + 'rad)')


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download