I have a div tag with id container. How can I find its center using either jquery or javascript?
<div id="container"></div>
here is css
#container {
width: 300px;
height: 300px;
border: 1px solid red;
}
Is it this?
var cX = $('#container').offset().left + $('#container').width()/2;
var cY = $('#container').offset().top + $('#container').height()/2;
$(function(){
var $this = $("#container");
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;
console.log(centerX ,centerY)
})
You should check:
width / outerWidth
height / outerHeight
jQuery way:
var div = $('#container');
var divCoords = {
x : div.width() * 0.5 ,
y : div.height() * 0.5
};
Related
I have a image and it is inside a div. I want to know what would be the lower co-ordinates for the image. Like if it a rectangle with corners A,B,C and D with A as the bottom left corner I want to get the co-ordinates of that. Could you let me know how I could achieve that using JavaScript or jQuery.
You can do this with JQuery position() and return left and top
var pos = $('img').position();
$('.result').append('(x: ' + pos.left + ', y: ' + pos.top + ')');
div {
width: 200px;
height: 200px;
position: relative;
border: 1px solid black;
}
img {
position: absolute;
left: 40px;
top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://placehold.it/50x50">
</div>
<span class="result"></span>
The best solution would be to use getBoundingClientRect()
var image = $( "img" );
var imageBounds = image.get(0).getBoundingClientRect();
var imageLeft = imageBounds.left;
var imageBottom = imageBounds.bottom;
Fiddle
But you could also use jQuery's .position() to get the top and left coordinates then to calculate the bottom and right position just add .height() or .width()
var image = $( "img" );
var imagePosition = image.position();
var imageHeight = image.height();
var imageLeft = imagePosition.left;
var imageBottom = imagePosition.top + imageHeight;
Fiddle
or without using jQuery:
var image = document.getElementById("image");
var imageBounds = image.getBoundingClientRect();
var imageLeft = imageBounds.left;
var imageBottom = imageBounds.bottom;
Fiddle
You can use .position() to get left and top coordinates(top left corner).
to get the bottom left corner just add image height to top coordinate.
$(window).load(function(){ //to make sure all images are loaded
console.log($('img').position().left);
console.log($('img').position().top + $('img').height());
});
div { padding: 30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><img src="http://placehold.it/350x150"></div>
Here is the demo on codepen: http://codepen.io/ssh33/pen/AXdVER
Waits for the image to download to get the width and height and calls GetCoordinates().
If the image has been previously cached $("#image").load() will never fire. In this case $(window).load() will call GetCoordinates() instead. GetCoordinates() checks for non-numeric width/height and retrieves it if necessary.
Recalculates on window resize.
var img_width, img_height, x, y;
$("#image").load(function() {
img_width = this.width;
img_height = this.height;
});
var GetCoordinates = function(){
if (isNaN(img_width) || isNaN(img_height)){
img_width = $("#image").width();
img_height = $("#image").height();
}
var img_left = $("#image").offset().left;
x = img_width + img_left;
var img_top = $("#image").offset().top;
y = img_height + img_top;
}
$(window).load(function() {
GetCoordinates();
});
$(window).resize(function() {
GetCoordinates();
});
I have a box, which I am trying to size perfectly to fit within the browser viewport if the image is not larger then it. So the image would appear to be centered within the window.
Currently I don' think my method of seeking the browser height is working. And for some reason there is a lot of extra space
Example (src)
here is where I define the page sizes
if ( style['img-width'] > screenwidth ) {
style['body-width'] = style['img-width'] + ( style['img-padding'] * 2 );
} else {
style['body-width'] = screenwidth;
}
style['body-height'] = ( style['img-height'] > screenheight ) ?
( style['img-height'] +
( style['img-padding'] * 2 ) +
style['header-height']
) :
screenheight;
$('body').css({ 'width': style['body-width']+'px' });
theater.css({
'width': style['body-width']+'px',
'height': style['body-height']+'px',
});
theaterheadcon.css('width', style['body-width']+'px');
theaterheader.css('width', style['body-width']+'px');
How I am defining screen width/height
screenwidth = isNaN(window.outerWidth) ? window.clientWidth : window.outerWidth,
screenheight = isNaN(window.outerHeight) ? window.clientHeight : window.outerHeight;
Here is the basic of centering items to a content with javascript and css:
/*css*/
#myImage
{
position:absolute;
}
And in java:
/*javascript*/
var img=$('#myImage');
var winWidth=$(window).width();
var winHeight=$(window).height();
if(img.height()>winHeight)
{
img.css('height', winHeight + "px");
}
img.css('left',(winWidth/2) + "px");
img.css('top',(winHeight/2) + "px");
img.css('margin-left',(-(img.width()/2)) + "px");
img.css('margin-top',(-(img.height()/2)) + "px");
The margin approach guaranties that the image will stay at the center even on page resize
I tried here in DIVs in your case code will detect your image size itself
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('height', windowheight).css('width', windowwidth);
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO
change your img width in css to see the action
if you want your div to not going outside the window after margin the image to center use that code
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('position','absolute').css('width', 'auto').css('height', 'auto').css('left', '0').css('top', '0').css('right', '0').css('bottom', '0');
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO
I have this markup:
<div class="container">
<figure></figure>
<figure></figure>
<figure></figure>
</div>
Now: I need to add for each of figures a symmetric element, but with different height and width value. For each item next I need to remove about 10% in width and height. So that the first has 90%, the second 80% and the third has 70% of initial size. I'm using the following code but it does not work, can anyone help?
var inside_element = $(figure);
var indx = 10;
inside_element.each(function(indx){
$(this).css({
width: '90%' - indx,
height: '90%' - indx
});
});
Thx.
You working on string '90%' and trying to complete math operation, which will fall. This should work:
var inside_element = $('figure');
var indx = 10;
inside_element.each(function(indx){
$(this).css({
width: (90 - (10*indx)) + '%' ,
height: (90 - (10*indx)) + '%'
});
});
Also declaration var indx = 10; is not necessary. This value will be overrided inside function.
EDIT: Also there can be more containers. Then code should look like this:
var inside_container = $('.inside_container');
inside_container.each( function(i) {
var inside_element = $(this).find('figure');
var step = 10;
inside_element.each(function(indx){
$(this).css({
width: (90 - (step*indx)) + '%' ,
height: (90 - (step*indx)) + '%'
});
});
});
You are calulating the next width and hight by substracting indx from a String.
try:
var width = 100;
var height = 100;
inside_element.each(function(indx){
width = width - 10;
height = height - 10;
$(this).css({
width: width + '%',
height: height + '%'
});
});
You are not selecting figure you need this $('figure');
var inside_element = $('figure');
inside_element.each(function(index){
$(this).css({
width: (90 - index * 10) +"%",
height:(90 - index * 10) +"%"
});
});
Try this:
var inside_element = $('figure');
var width = '90',
height = '90';
inside_element.each(function(indx){
$(this).css({
width: width + '%',
height: height + '%'
});
width = width - 10;
height = height - 10;
});
So I want to make the word "WIDTH" resize according to the width of the browser. Right now, only the box around the word resizes, but I want the word to resize as well. I feel like there's something wrong with my calculations.
<!DOCTYPE html>
<html>
<head>
<style>
#header{
margin: 0px;
font-size: 200px;
display:inline;
padding:0px;
position:absolute;
white-space:nowrap;
overflow:hidden;
border:thin solid black;
height:800px;
}
</style>
</head>
<body style="padding:0px;">
<div id="header"> WIDTH </div>
<script>
var text_div = document.getElementById("header");
var size = function (){
var winW = window.innerWidth;
var winH = window.innerHeight;
var win_ratio = winW/winH;
var offset_width = text_div.offsetParent.clientWidth;
var offset_height = text_div.clientHeight;
var offset_ratio = offset_width / offset_height;
text_div.style.width = offset_width + "px";
document.title = winW + ":" + offset_height;
text_div.style.fontSize=String(parseInt(winW/offset_ratio)) + "px";
}
window.onresize=function() {size();}
//size();
</script>
</body>
</html>
If you wrap your text in a span, you can get the text's offsetWidth
<div id="header"><span>WIDTH</span></div>
The div's width is fixed with left: 0px and right: 0px
#header {
position: absolute;
left: 0px;
right: 0px;
border: 1px solid black;
}
and the font-size is then adjusted dynamically. The for is there to prevent an endless loop
var epsilon = 5;
var div = document.getElementById('header');
var span = div.childNodes[0];
function size() {
var dw = div.offsetWidth;
var fs = 200;
span.style.fontSize = fs + 'px';
var cw = span.offsetWidth;
for (var i = 0; i < 10 && Math.abs(cw - dw) > epsilon; ++i) {
fs *= dw / cw;
span.style.fontSize = fs + 'px';
cw = span.offsetWidth;
}
}
window.onresize = size;
size();
JSFiddle
I'm not sure why you were using all the ratio stuff. Here's a simple example based on width alone.
http://jsfiddle.net/tHBpJ/3
var text_div = document.getElementById("header");
var initWinW = window.innerWidth;
var initFontSize = 40;
var size = function () {
var winW = window.innerWidth;
var textFactor = winW / initWinW
text_div.style.fontSize = initFontSize * textFactor + "px";
}
window.onresize = function () {
size();
}
I've used the jquery plugin fittext.js for this kind of thing in the past, and its worked quite nicely.
I want to draw gridlines of varying frequency on top of a static image in jquery, any suggestions as to the best/easiest approach - thanks!
// Specify the number of boxes
var verticalBoxes = 10;
var horizontalBoxes = 10;
var countBoxes = verticalBoxes*horizontalBoxes;
var imageHeight = img.height();
var imageWidth = img.width();
var boxHeight = imageHeight / verticalBoxes;
var boxWidth = imageWidth / horizontalBoxes;
// #grid needs to be relatively positioned
var grid = $('#grid').detach();
for(i = 0; i < countBoxes ; i++){
grid.append('<div class=\'boxes\'></div>');
}
// This is the absolutely positioned container overlaying the image
$('#grid-container').append(grid);
$('head').append('<style>.boxes {outline:1px solid black; height:'+boxHeight+'px; width:'+boxWidth+'px; float:left; }</style>');
I believe this version is more performant, relies on the CSS box model rather than placing each box individually. However it specifies the number of boxes rather than box size...
Here's a very quick mockup that should help give you an idea of my take
var top = image.top;
var left = image.left;
var width = image.width;
var height = image.height;
var boxHeight = 10; //change this how tall you want each grid box to be
var boxWidth = 10; //same for width
gridtop = top;
gridleft = left;
while (gridtop < top + height); {
gridtop += boxHeight;
$('body').append('<div></div>').css('position', 'absolute').css('width', width).css('top', gridtop).css('left', left);
}
while (gridleft < left + width); {
gridleft += boxWidth;
$('body').append('<div></div>').css('position', 'absolute').css('height', height).css('left', gridleft).css('top', top);
}