Position elements on screen using Javascript - javascript

I am attempting to use Javascript to position some of my elements on the screen/window. I am doing this to make sure that what ever the dimensions of the users screen, my elements will always be in the centre.
I know that padding & margin can also achieve this, but I am using a custom movement script called raphael.js, & in order to move my elements I need to set out my elements absolutely (its a custom home page, where you click blocks(that are links) & they fly off the screen).
My javascript function to move my elements fails to move my elements. Any suggestions on how to position my elements using javascript would be really helpful.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="dropDownMenu.js"></script>
<title></title>
<script src="javascript/raphael.js"></script> <!-- I am using a custom drawing/moving script which is why I cant put the img(id=bkImg) inside the div element -->
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
function getScreenSize()
{
var res = {"width": 630, "height": 460};
if (document.body)
{
if (document.body.offsetWidth) res["width"] = document.body.offsetWidth;
if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
}
if (window.innerWidth) res["width"] = window.innerWidth;
if (window.innerHeight) res["height"] = window.innerHeight;
alert( res["width"] );
alert( res["height"] );
return res;
}
function positionBlocksAccordingToScreenSize()
{
// The problem is that the blocks position does not change but they should?
var scrDim = getScreenSize();
var BK_WIDTH = 800;
var BK_HEIGHT = 600;
var X_OFFSET = (scrDim["width"]-BK_WIDTH) / 2; // variable that changes according to the width of the screen
var BLOCK_POS_X = [160, 80, 280, 20, 200, 400];
var BLOCK_POS_Y = [26, 203, 203, 380, 380, 380];
for ( var i=1; i<=5; i++ )
{
//document.getElementById("block"+i).setAttribute( "offsetLeft", X_OFFSET + BLOCK_POS_X[i] ); // doesn't work
//document.getElementById("block"+i).setAttribute( "offsetTop", BLOCK_POS_Y[i] ); // doesn't work
document.getElementById("block"+i).style.left = X_OFFSET + BLOCK_POS_X[i]; // doesn't work
document.getElementById("block"+i).style.top = BLOCK_POS_Y[i]; // doesn't work
}
}
-->
</script>
<style type="text/css" media="all">
<!--
#import url("styles.css");
#blockMenu { z-index: -5; padding: 0; position: absolute; width: 800px;
height: 600px; /*background-image: url("images/menuBk.png");*/ }
#bkImg { z-index: -5; position: relative; }
#block1 { z-index: 60; position: absolute; top: 26px; left: 160px; margin: 0; padding: 0; }
#block2 { z-index: 50; position: absolute; top: 203px; left: 80px; margin: 0; padding: 0; }
#block3 { z-index: 40; position: absolute; top: 203px; left: 280px; margin: 0; padding: 0; }
#block4 { z-index: 30; position: absolute; top: 380px; left: 20px; margin: 0; padding: 0; }
#block5 { z-index: 20; position: absolute; top: 380px; left: 200px; margin: 0; padding: 0; }
#block6 { z-index: 10; position: absolute; top: 380px; left: 400px; margin: 0; padding: 0; }
-->
</style>
</head>
<body onload="positionBlocksAccordingToScreenSize()" style="margin-top: 10%; text-align: center; margin-bottom: 10%; position: relative;">
<img id="bkImg" src="images/menuBk.png" width="800px;" height="600px" alt=""/>
<!-- The above image should be displayed behind the below div. I am using the raphael.js movement script, so I cannot place
this image inside the div, because it will get erased when I call raphael.clear(); -->
<div id="blockMenu">
<div id="block1"><img src="images/block1.png" width="200" height="200"/></div>
<div id="block2"><img src="images/block2.png" width="200" height="200"/></div>
<div id="block3"><img src="images/block3.png" width="200" height="200"/></div>
<div id="block4"><img src="images/block4.png" width="200" height="200"/></div>
<div id="block5"><img src="images/block5.png" width="200" height="200"/></div>
<div id="block6"><img src="images/block6.png" width="200" height="200"/></div>
</div>
</body>
</html>

You're not setting the left and top properties correctly, you need to add the unit e.g 'px' for pixels.
document.getElementById("block"+i).style.left = X_OFFSET + BLOCK_POS_X[i] + 'px';
document.getElementById("block"+i).style.top = BLOCK_POS_Y[i] + 'px';

"Would you be able to suggest a line of jQuery code that could place my elements correctly?"
The following code uses jQuery and will center an absolutely positioned element on load and on window resize.
http://jsfiddle.net/Fu3L6/
HTML...
<div id="element">Test</div>
CSS...
#element {
position: absolute;
background-color: red;
width: 200px;
}
jQuery...
$(document).ready(function () {
centerInViewport('#element');
$(window).resize(function () {
centerInViewport('#element');
});
});
function centerInViewport(e) {
$docWidth = $(document).width();
$elWidth = $(e).width();
$offset = ($docWidth - $elWidth) / 2;
$(e).css("marginLeft", $offset + "px");
}

Related

CSS animation. transition applies to all the other times, but not the first time

I'm trying to make a sample where when the user click on the window, the circle (div) will move to that place with a transition. However, it does not work on the first click, but all the others. So I wonder what's making it do that.
<!doctype html>
<html>
<head>
<title>Hover</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="CSS/mystyles.css" >
</head>
<body>
<div id = "divGroup" class = 'group'>
</div>
<script src="JS/code.js"></script>
</body>
</html>
the javascript (i'm using javascript to receive the values and define new values:
var divGroup = document.getElementById("divGroup");
window.onclick = function(evt) {
divGroup.style.left = (evt.clientX - 25) + "px";
divGroup.style.top = (evt.clientY - 25) + "px";
}
the css:
#divGroup {
width: 50px;
height:50px;
background-color:lightblue;
border-radius:50%;
position: absolute;
transition: all 0.5s;
}
You should add initial left and top values in css for #divGroup
var divGroup = document.getElementById("divGroup");
window.onclick = function(evt) {
divGroup.style.left = (evt.clientX - 25) + "px";
divGroup.style.top = (evt.clientY - 25) + "px";
}
#divGroup {
width: 50px;
height: 50px;
background-color: lightblue;
border-radius: 50%;
position: absolute;
transition: all 0.5s;
left: 0;
top: 0;
}
<div id="divGroup" class='group'>

Set maximum and minimum width of div during re-size

Sorry for the ambiguous title, not sure how to phrase it.
I have an html page that has 2 iframes side by side with 100% height. I'm trying to set the maximum width of the iframe on right.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="holder_Iframe1">
<iframe id="iframe1" src="https://en.wikipedia.org/wiki/Mercedes-Benz"></iframe>
<div id="drag"></div>
</div>
<div id="holder_Iframe2">
<iframe id="iframe2" src="http://www.dictionary.com/browse/mercedes?s=t"></iframe>
</div>
</div>
</div>
</body>
</html>
Both iframes are wrapped by divs. Hover the mouse between the iframes to be see the re-size cursor.
I'm setting a maximum width of the iframe2 (the one on the right) of 560px, but when resizing, sometimes it passes that maximum width so I can't resize it back. I'm trying to fix that.
function Resize(e) {
var rightPanePx = document.documentElement.clientWidth - parseInt(holder_Iframe1.style.width, 10);
console.log(rightPanePx);
if ((rightPanePx >= 25) && (rightPanePx <= 560)) {
holder_Iframe1.style.width = (e.clientX - holder_Iframe1.offsetLeft) + "px";
iframe1.style.width = Math.max((holder_Iframe1.style.width.replace("px", "") - 4), 0) + "px";
holder_Iframe2.style.width = (document.documentElement.clientWidth - holder_Iframe1.style.width.replace("px", "")) + "px";
iframe2.style.width = holder_Iframe2.style.width;
}
}
I have attached the code that demonstrates my problem.
var iframe1 = document.getElementById("iframe1");
var iframe2 = document.getElementById("iframe2");
var holder_Iframe1 = document.getElementById("holder_Iframe1");
var holder_Iframe2 = document.getElementById("holder_Iframe2");
var dragEl = document.getElementById("drag");
holder_Iframe1.style.width = (Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * 0.8) + "px";
iframe1.style.cssText = 'width:' + ((Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * 0.8) - 5) + 'px;height:100%;';
dragEl.addEventListener('mousedown', function(e) {
//create overlay so we will always get event notification even though the pointer is hovering iframes
var overlay = document.createElement('div');
overlay.id = "overlay";
document.body.insertBefore(overlay, document.body.firstChild);
window.addEventListener('mousemove', Resize, false);
window.addEventListener('mouseup', stopResize, false);
}, false);
function Resize(e) {
var rightPanePx = document.documentElement.clientWidth - parseInt(holder_Iframe1.style.width, 10);
console.log(rightPanePx);
if ((rightPanePx >= 25) && (rightPanePx <= 560)) {
holder_Iframe1.style.width = (e.clientX - holder_Iframe1.offsetLeft) + "px";
iframe1.style.width = Math.max((holder_Iframe1.style.width.replace("px", "") - 4), 0) + "px";
holder_Iframe2.style.width = (document.documentElement.clientWidth - holder_Iframe1.style.width.replace("px", "")) + "px";
iframe2.style.width = holder_Iframe2.style.width;
}
}
function stopResize(e) {
//remove event listeners from improved performance
window.removeEventListener('mousemove', Resize, false);
window.removeEventListener('mouseup', stopResize, false);
//remove fake overlay
document.getElementById("overlay").remove();
}
html {
overflow-y: hidden;
}
body {
width: 100%;
}
iframe,
#holder_Iframe1,
#holder_Iframe2 {
margin: 0;
padding: 0;
border: 0;
}
iframe {
width: 100%;
height: 100%;
min-width: 0;
}
#content-wrapper {
display: table;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
position: absolute;
}
#content {
display: table-row;
}
#holder_Iframe1,
#holder_Iframe2 {
display: table-cell;
min-width: 0 !important;
}
#holder_Iframe1 {
width: 80%;
}
#drag {
height: 100%;
width: 3px;
cursor: col-resize;
background-color: rgb(255, 0, 0);
float: right;
}
#drag:hover {
background-color: rgb(0, 255, 0);
}
#drag:active {
background-color: rgb(0, 0, 255);
}
#overlay {
background-color: rgba(0, 0, 0, 0);
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
cursor: col-resize;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="holder_Iframe1">
<iframe id="iframe1" src="https://en.wikipedia.org/wiki/Mercedes-Benz"></iframe>
<div id="drag"></div>
</div>
<div id="holder_Iframe2">
<iframe id="iframe2" src="http://www.dictionary.com/browse/mercedes?s=t"></iframe>
</div>
</div>
</div>
</body>
</html>
You need to use cursor's position to detect where the direction is.
By adding e.pageX to your function to determine whether resize it or not.
In your sample this may be if (window_size - e.pageX < 560) go resize it, otherwise don't resize.

How to add text to different parts of chart made from css, html, and javascript?

I'd like to add text to three different parts of the below row chart:
http://codepen.io/chriscruz/pen/ByjZdp
A number at the beginning of where the orange begins
a percentage right before the organge ends
A number at the end of the entire bar where the gray ends.
Something like this:
HTML:
<div class="progress-wrap progress" data-progress-percent="50">
<div class="progress-bar-state progress">50</div>
</div>
CSS:
.progress {
width: 100%;
height: 50px;
}
.progress-wrap {
background: #f80;
margin: 20px 0;
overflow: hidden;
position: relative;
.progress-bar-state {
background: #ddd;
left: 0;
position: absolute;
top: 0;
}
}
Javascript:
// on page load...
moveProgressBar();
// on browser resize...
$(window).resize(function() {
moveProgressBar();
});
// SIGNATURE PROGRESS
function moveProgressBar() {
console.log("moveProgressBar");
var getPercent = ($('.progress-wrap').data('progress-percent') / 100);
var getProgressWrapWidth = $('.progress-wrap').width();
var progressTotal = getPercent * getProgressWrapWidth;
var animationLength = 2500;
// on page load, animate percentage bar to data percentage length
// .stop() used to prevent animation queueing
$('.progress-bar-state').stop().animate({
left: progressTotal
}, animationLength);
}
I've tried to just insert the numbers after, but I can't seem to make the numbers relative to the position of 'progress-wrap' or 'progress.' See my attempt here: http://codepen.io/chriscruz/pen/MYKoBq
You can use :before and :after :pseudo-elements.
// on page load...
moveProgressBar();
// on browser resize...
$(window).resize(function() {
moveProgressBar();
});
// SIGNATURE PROGRESS
function moveProgressBar() {
console.log("moveProgressBar");
var getPercent = ($('.progress-wrap').data('progress-percent') / 100);
var getProgressWrapWidth = $('.progress-wrap').width();
var progressTotal = getPercent * getProgressWrapWidth;
var animationLength = 2500;
// on page load, animate percentage bar to data percentage length
// .stop() used to prevent animation queueing
$('.progress-bar-state').stop().animate({
left: progressTotal
}, animationLength);
}
.progress {
width: 100%;
height: 50px;
}
.progress-wrap:before {
content: '66';
position: absolute;
left: 5px;
line-height: 50px;
}
.progress-wrap:after {
content: '$250,000';
right: 5px;
position: absolute;
line-height: 50px;
}
.progress-wrap {
background: #f80;
margin: 20px 0;
overflow: hidden;
position: relative;
}
.progress-wrap .progress-bar-state {
background: #ddd;
left: 0;
position: absolute;
top: 0;
line-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Change the below data attribute to play -->
<div class="progress-wrap progress" data-progress-percent="50">
<div class="progress-bar-state progress">50</div>
</div>
As given below, Add/Modify HTML , CSS and JS. It gets your desired output
$('.progress-bar-state').stop().animate({
left: progressTotal
width:getProgressWrapWidth - progressTotal
}, animationLength);
HTML
<!-- Change the below data attribute to play -->
<div class="progress-wrap progress" data-progress-percent="7">
vd
<div class="progress-bar-state progress">8
<div class="right-content" >RightEnd</div></div>
</div>
CSS
.right-content
{
float:right;
}

jitter when using jquery to alter background-position

Here's the jsfiddle.
It's the interface to cropping an image. As you can see the selection div takes the same background image and positions it to the negative of the top and left attributes of the selection div. In theory this should give a perfect overlap, but there's a jitter as you move the selection div around, and I can't seem to figure out what is causing it.
html
<div id="main">
<div id="selection"></div>
</div>
css
#main {
width: 600px;
height: 450px;
position: relative;
background: url("http://cdn-2.historyguy.com/celebrity_history/Scarlett_Johansson.jpg");
background-size: contain;
}
#selection {
width: 100px;
height: 100px;
position: absolute;
background: url("http://cdn-2.historyguy.com/celebrity_history/Scarlett_Johansson.jpg");
border: 1px dotted white;
background-size: 600px 450px;
}
jquery
$(document).ready(function () {
var move = false;
var offset = [];
var selection = null;
$("#selection").mousedown(function (e) {
move = true;
selection = $(this);
offset = [e.pageX - selection.offset().left, e.pageY - selection.offset().top];
});
$("#selection").mousemove(function (e) {
if (move == true) {
selection.css("left", e.pageX - offset[0]);
selection.css("top", e.pageY - offset[1]);
selection.css("background-position", (((-selection.position().left) - 1) + "px " + ((-selection.position().top ) - 1) + "px"));
}
});
$("#selection").mouseup(function (e) {
move = false;
});
})
It would appear that there is a value of 5 offset that needs to be added to ensure seamlessness
DEMO http://jsfiddle.net/nzx0fcp5/2/
offset = [e.pageX - selection.offset().left + 5, e.pageY - selection.offset().top + 5];
So, while experimenting I discovered that this was only a problem at certain sizes of the image. At the original size it is no problem, neither at half nor a quarter of this size. It wasn't simply a matter of keeping the image in proportion not having the image square or using even pixel sizes. I'm assuming this had something to do with partial pixel sizes, but I'm not sure, and I couldn't see any way to work around this, at least none that seemed worth the effort.
So while checking out the code of other croppers I took a look at POF's image cropper, they seem to have got round the problem by not using the background-position property at all (I'm not sure if it's plugin or they coded it themselves). They just set the image down and then used a transparent selection div with 4 divs stuck to each edge for the shading. So there's no pixel crunching on the fly at all. I like the simplicity and lightweight nature of this design and knocked up a version myself in jsfiddle to see if I could get it to work well.
new jitter free jsfiddle with no pixel crunching
I liked the solution for the preview box as well.
html
<body>
<div id="main">
<img src="http://flavorwire.files.wordpress.com/2012/01/scarlett_johansson.jpg" />
<div id="upperShade" class="shade" > </div>
<div id="leftShade" class="shade" > </div>
<div id="selection"></div>
<div id="rightShade" class="shade"></div>
<div id="lowerShade" class="shade" ></div>
</div>
</body>
css
#main {
position:relative;
width: 450px;
height: 600px;
}
#selection {
width: 148px;
height: 148px;
position: absolute;
border: 1px dotted white;
top: 0px;
left: 0px;
z-index: 1;
}
.shade {
background-color: black;
opacity: 0.5;
position: absolute;
}
#upperShade {
top: 0px;
left: 0px;
width: 600px;
}
#leftShade {
left: 0px;
top: 0px;
height: 150px;
width: auto;
}
#rightShade {
left: 150px;
top: 0px;
height: 150px;
width: 450px;
}
#lowerShade {
left:0px;
top: 150px;
width: 600px;
height: 300px;
}
jquery
$(document).ready(function () {
var move = false;
var offset = [];
var selection = null;
$("#selection").mousedown(function (e) {
move = true;
selection = $(this);
offset = [e.pageX - selection.offset().left, e.pageY - selection.offset().top];
});
$("#selection").mousemove(function (e) {
if (move == true) {
selection.css("left", e.pageX - offset[0]);
selection.css("top", e.pageY - offset[1]);
setShade();
}
});
function setShade() {
$("#upperShade").css("height", selection.position().top);
$("#lowerShade").css("height", 600 - (selection.position().top + 150));
$("#lowerShade").css("top", selection.position().top + 150);
$("#leftShade").css("top", selection.position().top);
$("#leftShade").css("width", selection.position().left);
$("#rightShade").css("top", selection.position().top);
$("#rightShade").css("left", selection.position().left + 150);
$("#rightShade").css("width", 450 - selection.position().left);
}
$("#selection").mouseup(function (e) {
move = false;
});
});

javascript mouseout function flickering

I'm trying to create a mouse in and out effect that shows and disappears DIV's according to the mouse function. I've successfully done this, but the mouseout function flickers on and off when im inside the div instead of staying on.
Heres my sample code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Kow Your Face</title>
<style>
#face {
background-image: url(face.png);
width: 262px;
height: 262px;
}
#lefteye {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 69px;
left: 59px;
}
#righteye {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 41px;
left: 167px;
}
#mouth {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 84px;
left: 114px;
}
</style>
</head>
<body>
<div id="face">
<div id="lefteye" onMouseOver="getElementById('lefteye').style.visibility='hidden'; getElementById('lefteyedes').style.visibility='visible';" onMouseOut="getElementById('lefteye').style.visibility='visible'; getElementById('lefteyedes').style.visibility='hidden';">
</div>
<div id="righteye" onMouseOver="getElementById('righteye').style.visibility='hidden'; getElementById('righteyedes').style.visibility='visible';" onMouseOut="getElementById('righteye').style.visibility='visible'; getElementById('righteyedes').style.visibility='hidden';">
</div>
<div id="mouth" onMouseOver="getElementById('mouth').style.visibility='hidden'; getElementById('mouthdes').style.visibility='visible';" onMouseOut="getElementById('mouth').style.visibility='visible'; getElementById('mouthdes').style.visibility='hidden';">
</div>
</div>
<div id="lefteyedes" style="visibility: hidden;">
<p>Left Eye</p>
</div>
<div id="righteyedes" style="visibility: hidden;">
<p>Right Eye</p>
</div>
<div id="mouthdes" style="visibility: hidden;">
<p>Mouth</p>
</div>
</body>
</html>
Use document.getElementById instead of just getElementById and you can use this keyword to refer to the current element:
<div id="lefteye" onMouseOver="this.style.visibility='hidden'; document.getElementById('lefteyedes').style.visibility='visible';" onMouseOut="this.style.visibility='visible'; document.getElementById('lefteyedes').style.visibility='hidden';">
</div>
For some reason your onmouseout function is being repeatedly called "onmousemove"...this solution should help you suppress the onmouseout function being repeatedly called. I've rewritten your code a little to help make it easier to enforce changes later (illustrated with one of the onmouseover/onmouseout pairs)...give this a shot:
<script type="text/javascript">
function leftEyeVisibility(vis1, vis2) {
//this function should work for the left eye when the left eye is hidden (lefteyedes is visible) and the mouse is moving over (or not moving at all) the hidden left eye div but has not moused out of it
var dg = document.getElementById("lefteye");
var divStyle = window.getComputedStyle(dg, "");
var mousePosition = function (e) {
var xCoord = e.pageX;
var yCoord = e.pageY;
return xCoord + "," + yCoord;
}
var positionArray = mousePosition.split(","); //split the xy coordinates returned by previous function
if ((positionArray[0] > dg.offsetLeft) && (positionArray[0] < dg.offsetLeft + dg.offsetWidth) && (positionArray[1] > dg.offsetTop) && (positionArray[1] < dg.offsetTop + dg.offsetHeight)) {
var mouseOverlap = 'yes';
} else var mouseOverlap = 'no';
if ((divStyle.visibility === 'hidden') && (mouseOverlap === 'yes')) {
return false;
} else {
document.getElementById("lefteye").style.visibility = vis1;
document.getElementById("lefteyedes").style.visibility = vis2;
}
}
</script>
<div id="lefteye" onmouseover="leftEyeVisibility('hidden', 'visible')" onmouseout="leftEyeVisibility('visible', 'hidden')">
</div>
With jQuery it would be much easier to do this...let me know if it works.

Categories

Resources