Positioning element relative to another not working - javascript

I'm trying to position an element relative to another using the jQuery offset() method and I am trying to figure out why the $(window).resize function is not working.
JSBIN:http://jsbin.com/lanako/7/edit?html,js,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<style>
div{
display:inline-block;
position:relative;
height:200px;
width:200px;
border:solid black;
}
#somepara{
border: solid blue;
position:relative;
left:20%;
}
</style>
<body>
<div id ="first"> FIRST</div>
<div id = 'somepara'> </div>
</body>
</html>
JavaScript:
var p = $( "#somepara" );
var pf = $('#first');
var offset = p.offset();
p.html( "left: " + offset.left);
function offcss(){
pf.css({'left': offset.left + 6 + "px"});
}
$(document).ready(function(){
offcss();
$(window).resize(function(){
offcss();
});
});
I am essentially grabbing the offset().left of the second element ('#somepara') and trying to set the css of ('#first') right 6 pixels from (#somepara).Note: (#somepara) is has a fluid measurement (%), so the left position changes.
The equation initially works, but I want to upon resizing the browser, for the equation pf.css(), which calculates the css left property of (#first) to execute. Unfortunately the $(window).resize function I have set is not working, and thus the left property of (#first) is unchanged. The end goal I want is regardless the browser size, the elements will be separated by 6 pixels (#first right 6 pixels from #somepara).
Any help would be greatly appreciated!

The position of #somepara changes when you resize, so you need to take the value of p.offset() every time you call the offcss() function (and not only on first load).
function offcss() {
pf.css({'left': p.offset().left + 6 + "px"});
}
Regarding the resize it seems like it does exactly what you want.
Check this example:
http://jsbin.com/dewazuyuqo/1/edit?html,js,output

Related

Grid display separates when viewed fullscreen

I'm having trouble understanding whats going on with a grid I created. I made some code for a grid via javascript that changes the cell color when the mousepointer passes over it, however whenever I view this grid in a fullscreen window the view of the grid changes to four separate columns. This only happens when I look at the grid in fullscreen however, when viewing the grid in any smaller sized window it looks exactly how you envison a grid; with no spaces in between columns.
gridProblem
This is how the grid looks fullscreen with the spacing issue shown
grid solution
This is how the grid looks in any window sizing outside of maximized, and how I would like the grid to display 100% of the time.
Just in case, here is the code I'm using:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Etch N Sketch</title>
</head>
<body>
<div class="container" id="container"></div>
<script src="script.js"></script>
</body>
</html>
Javascript:
const board = document.getElementById("container");
for (x=0; x <= 15; x++) {
const cell = document.createElement('div');
cell.className = "cells";
cell.setAttribute("style", "height: 200px; width: 200px; color: black;");
cell.style.backgroundColor = "blue";
cell.style.border = "solid 2px";
cell.style.borderColor = "black";
board.style.columnGap = "0px";
board.style.display ="grid";
board.style.gridTemplateColumns = "auto auto auto auto";
board.appendChild(cell);
cell.addEventListener("mouseover", change = () =>
cell.style.backgroundColor = "red")
cell.addEventListener("mouseout", reset = () => cell.style.backgroundColor = "blue")
}
The issue is that you set the width and height to be absolute values here
cell.setAttribute("style", "height: 200px; width: 200px; color: black;");
so at a smaller screen size 200px is fine but once the area that the squares need to cover becomes larger than 200px your limiting them by having these values tied to them.

Why are Document Size and Window Size the Same On Load?

I am storing the offset of a div as a percentage of document size ({position_x: 0.50, position_y: 0.50} for example). That number is then multiplied by document width/height to get a pixel value I use to set the div's offset. The problem is that when first loading the document, document size and window size are being calculated as the same thing, so {position_x: 0.50, position_y: 0.50} is 50% of the window's 500px width/height and not the document's 1200px width/height. How can I get document size to render completely before setting the offset?
$(function() {
var offset= {
position_x: 0.5,
position_y: 0.5
};
var offsetLeft = $(document).width() * offset.position_x;
var offsetTop = $(document).height() * offset.position_y;
$(".square").css({top: offsetTop, left: offsetLeft});
});
.square
{
height: 100px;
width: 100px;
border: 1px solid black;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Document Size Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div class='square'></div>
</body>
</html>
Generally document means the entire HTML document. Since you try to retrieve the height of document, as only the html window is visible, it gives the size of browser screen. But, in case of window, it targets the browser window. Eventually, both things are same at the initials.

Setting height relative to `window.innerHeight` not working

This might be a very stupid question for some people, but I surely am not able to understand the problem behind this. The code is fairly simple, and goes as follows:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>####</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body onload="resizeDiv();">
<div id="testElement">ABCD</div>
<div id="secElement">ABC</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
CSS:
html , body{
height:100%;
}
#testElement{
background-color:black;
color:white;
}
#secElement{
font-size:50px;
}
JS:
(function immediate(){
document.getElementById('secElement').textContent = window.innerHeight;
}());
function resizeDiv(){
document.getElementById('testElement').style.height = (window.innerHeight - 50) * 0.9;
}
Now, by this code, the div with id 'testElement' should have an height which is 90% of the window.innerHeight - 20. But, nothing seems to work. Please help.
Add "px":
document.getElementById('testElement').style.height = (window.innerHeight - 50) * 0.9 + "px";
body tag has a onload handler assigned to resizeDiv() but your script is at the bottom of the page so, the onload handler can't refer to it.
Use document.getElementById('testElement').setAttribute("style","height:" + (window.innerHeight - 50) * 0.9) + ' px'; You can find more explanation why to use it here: Setting DIV width and height in JavaScript

Alternatives to resizing background images

I am creating a website that has this kind of structure:
Where the red box represents the user's browser window. When the user clicks a button on the home (bottom), it slides up to the new scene (stratosphere for example). Each scene is an entire image. Now the problem is, I need to account for users using different screen sizes and when they resize the window. I've looked up ways to resize backgrounds images using CSS or JavaScript, and that doesn't work well for me. I need to find some way to make them all fit for everyone using different screen sizes. An idea I have - I know this sounds clunky but would it be viable to write a PHP script which resizes an image to the dimension given by the JS? JS finds the browser window's size, hands it to PHP, PHP returns the image JS needs. And have this happen when a user resizes the browser window too...
How can I do this?
Update:
I tried SVG, and it's working beautifully. But now I am wondering how I can get the other elements to be in accordance with the SVG?
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
<meta name="generator" content="TextMate http://macromates.com/">
<!-- Date: 2012-08-01 -->
<style type="text/css" media="screen">
body { margin: 0px; }
.area { border: 3px solid red; background: green; margin-bottom: 0px; background: url(http://www.alistapart.com/d/using-svg-for-flexible-scalable-and-fun-backgrounds-part-ii/beetle.svg) no-repeat; }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
function scroll_to(id, speed, margin) {
$('html, body').animate({
scrollTop: $('#' + id).offset().top - margin
}, speed);
}
var slide = 'a3'
$(".area").height($(window).height());
$(window).resize(function() {
$(".area").height($(window).height());
$(".area").width($(window).width());
scroll_to(slide, 1, 0);
});
scroll_to('a2', 'slow', 0);
});
</script>
</head>
<body>
<div class="area" id="a3">
<h1>scene 3</h1>
</div>
<div class="area" id="a2">
<h1>scene 2</h1>
<div style="height: 100px; border: 1px solid black;" id="text">
hi
</div>
</div>
<div class="area" id="a1">
<h1>scene 1</h1>
</div>
</body>
</html>
Why don't you use an SVG as background image? Your scene seems fairly simple.
All browser but IE ≤ 8 understand background: url(some.svg): http://caniuse.com/svg-css
Use one large background-image. Set it up with something like this:
html, body {
margin: 0;
padding: 0;
width: 100%
}
body {
position: absolute;
bottom: 0;
height: 2000px;
background-image: url('background.png')
}
Then use JavaScript to set the bottom property of body to move up, like this:
window.addEventListener('keydown', keypressed, false);
function keypressed(e) {
if(String.fromCharCode(e.charCode) == ' ') {
document.body.style.bottom += parseInt(document.body.style.bottom) + 10 + 'px';
}
}
I'm afraid re-sizing the background image is going to be your best bet. Why don't you post the code you've already tried for such a solution and others can help you along from that angle.
You should definitely split the image into multiple images, one for each tab.
This is how I would do it: http://jsfiddle.net/4CwdX/3/
You don't need to resize the image. The browser can automatically stretch it for you with background-size: 100%.

Scroll content automatically in an overflow:none element (jQuery)

I have mixed content (images, text) in an overflow:none element. Now, I'd like to automatically scroll that content in x/y axis based on the location of the mouse pointer. Overflow:auto wouldn't be an option, as I wouldn't like to show/use the scrollbars in that element.
I've found a script which does something similar, but only with the background image. Is there a way to have a similar effect but with moving the whole content of the div? Thank you for your answers in advance!
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test jQuery Move Background with Mouse Move</title>
<link rev="made" href="mailto:covertlinks [ at ] gmail [ dot ] com" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="generator" content="NoteTab Pro 5.5" />
<meta name="author" content="Perry Wolf" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var vH=$('#viewer').height();
var vW=$('#viewer').width();
var vT=$('#viewer').offset().top;
var vL=$('#viewer').offset().left;
$('#viewer').mousemove(function(e){
var ypos=e.pageY-vT;
var xpos=e.pageX-vL;
var y=Math.round(ypos/vW*100);
var x=Math.round(xpos/vH*100);
$('#test').val(x+' , '+y);
$('#viewer').css({backgroundPosition: x+'% '+y+'%'});
});
});
</script>
</head>
<body style="color:#FFFFFF;background:#102030;text-align:center;">
<h1 style="text-align:center;">Test Move Background on Mousemove:</h1>
<div id="viewer" style="border:solid 1px #FFFFFF;margin:50px auto 0px auto;width:400px;height:400px;background:url(ironhide1024x768.jpg) 0% 0% no-repeat;cursor:url(target_cursor.gif), crosshair;text-align:center;line-height:300px;">
</div>
<input type="text" id="test" size="30" style="display:block;margin:10px auto;width:150px;" />
</body>
</html>
This was a fun one! Change it so you move the scrollTop and scrollLeft instead of background position. Since you have a percentage you could calculate the of scrollTop and scrollLeft like so. Check out the fiddle.
$(document).ready(function(){
var viewer = $('#viewer'),
vH = viewer.height(),
vW = viewer.width(),
vT = viewer.offset().top,
vL = viewer.offset().left,
sTop = viewer.find(':first').height() + 18 - vH,
sLeft = viewer.find(':first').width() + 18 - vW;
// the sTop and sLeft could be calculated differently. In this case
// I am assuming that the viewer has a single child that is larger than itself.
// realistically this should check total possible scrollTop and scrollLeft
$('#viewer').mousemove(function(e){
var $this = $(this),
y = (e.pageY-vT)/vH,
x = (e.pageX-vL)/vW;
$this.scrollTop(Math.round(sTop * y))
.scrollLeft(Math.round(sLeft * x));
});
});

Categories