I want to position my markers when zoom 18 += 10px up, so what I dit is this:
his._mapsWrapper.subscribeToMapEvent<void>('zoom_changed').subscribe(() => {
this._mapsWrapper.getZoom().then((z: number) => {
this._zoom = z;
if(z === 18) {
$('.marker').css({ 'width' : '25px', 'height' : '25px', 'line-height': '25px', 'top' : '+= 10!important' });
$('.number-id').css({'font-size': '11px'})
}
But it seems not to work can somebody help me out here? Here is a PLUNKER, where you can see this code in src/google-maps/directive/google-map.ts in the method _handleMapZoomChange()
What it does it is setting all the elements to 10px, but what I basically wants is to set the current top position + 10px.
$('.marker').each( function (index) {
console.log(index + ":" + $(this).css('top'));
var currentTop = $(this).css('top');
$(this).css('top', currentTop + '10px');
})
If you are using custom overlay, it can cause unexpected behaviour if you adjust left or top position of the marker, because that is tied to latLng position of the marker.
Instead, just use margin-top css attribute (margin-top: 10px or margin-top: -10px depending on your needs)
The same thing when drawing the marker, don't adjust position like this:
if (point) {
div.style.left = (point.x - 10) + 'px';
div.style.top = (point.y - 10) + 'px';
}
Instead add the offset as margin-top and margin-left to your marker's css:
div.style.cssText = `width: 25px;
height: 25px;
...
margin-top: -10px;
margin-left: -10px;`
Related
I trying to create a map framework for some games and i have a problem with recalc position of marker. Look url to test, with wheel you can resize div with image but the dot red not come back to own position. Sorry but im new on this y trying to learn more about js and css. Thanks
$('.map-live').css('width', "928px");
$('.map-live').css('height', "928px");
$('.map-live').css('background-size', "100%");
$('.map-live').bind('mousewheel DOMMouseScroll', function(event) {
var divSize = $('.map-live').css('width');
console.log(divSize);
divSize = divSize.replace('px', '')
divSize = parseInt(divSize);
console.log("oldSize: " + divSize);
var delta_px = event.originalEvent.wheelDelta > 0 ? (divSize + (divSize * 0.15)) : (divSize - (divSize * 0.15));
console.log("NewSize: " + delta_px);
$(this).css('width', delta_px + "px");
$(this).css('height', delta_px + "px");
$(this).css('background-size', "100%");
UpdatePoints();
});
$(function() {
$("#map-live").draggable();
});
document.getElementById('map-live').addEventListener('click', printPosition)
function getPosition(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
return {
x,
y
}
}
function printPosition(e) {
var position = getPosition(e);
console.log('X: ' + position.x + ' Y: ' + position.y);
var divX = parseInt($('.map-live').css('width').replace('px', ''));
var divY = parseInt($('.map-live').css('height').replace('px', ''));
var vhX = (position.x / divX) * 100;
var vhY = (position.y / divY) * 100;
console.log('vhX: ' + vhX + ' vhY: ' + vhY);
}
function UpdatePoints() {
$('.point').css('top', '2.477565353101834vh');
$('.point').css('left', '2.477565353101834vh');
$('.point').css('position', 'absolute');
}
body {
margin: 0;
overflow: hidden;
}
.map-live {
position: absolute;
left: 10px;
z-index: 9;
background-image: url(https://i.ibb.co/d2y5G1y/map.jpg);
width: 222px;
height: 222px;
transition: all 0.2s linear;
}
.point {
position: absolute;
left: 2.477565353101834vh;
top: 2.477565353101834vh;
width: 10px;
height: 10px;
background-color: red;
border-radius: 50%;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="map-live ui-widget-content" id="map-live">
<div class="point"></div>
</div>
jsfiddle.net/f84mto52
Someone can correct me, but I believe your use of position: absolute is what is making the <div class="point"></div> stay in place.
Your UpdatePoints is setting always the same position in the div. With 'vh' you are calculating and absolute position proportional to viewport, no to parent container.
So, you are zooming the background image but the position (x, y) will be always be (x, y), positions are not zoomed. You need to recalculate which is the new position.
So you need to calculate new position.
function UpdatePoints(){
var divW = parseInt($('.map-live').css('width').replace('px',''));
var divH = parseInt($('.map-live').css('height').replace('px',''));
var topPosition = (2.477565353101834 / 928) * divH;
var leftPosition = (2.477565353101834 / 928) * divW;
$('.point').css('top', topPosition+'vh');
$('.point').css('left', leftPosition+'vh');
$('.point').css('position', 'absolute');
}
Also, instead using 'vh' I recommend to calculate the px position instead. I have added the already calculated delta_px parameter to UpdatePoints function:
<style>
.point {
position: absolute;
left: 22.99180647678502px;
top: 22.99180647678502px;
width: 10px;
height: 10px;
background-color: red;
border-radius: 50%;
}
</style>
<script>
function UpdatePoints(delta_px){
var position = (delta_px/100)*2.477565353101834;
$('.point').css('top', position+'px');
$('.point').css('left', position+'px');
$('.point').css('position', 'absolute');
}
</script>
Also, here we are calculating the top-left position of the .point element, not the position for the center. As it is a circle, it work fine, but if you use any other shape the position translation should be calculated from its center.
I recommend to do some research about how to translate elements. You can start here:
Calculating relative position of points when zoomed in and enlarged by a rectangle!
Zoom in on a point (using scale and translate)!
How do I effectively calculate zoom scale?!
EDIT 3/Final: Th Computed Style problem/question is explained below but, for the benefit of others coming later, my real problem is solved with Flex Boxes and Vx measurements in conjunction with border-box. IMHO "display: flex;" is the answer to many questions and, although I'm struggling to get it to do what I want, stops you having to work against CSS!
EDIT 2: The following undoubtedly needs refactoring but if you can tell me that it does what I was asking for that'd be great. The change I had to make was to add clientTop in with offsetTop in the equation: -
function resizeContent()
{
var browserHeight = window.outerHeight;
var offesetHeight, offsetWidth;
var viewHeight = window.innerHeight;
var viewWidth = window.innerWidth;
var chromeFootPrint = browserHeight - viewHeight;
var tmpHeight = viewHeight;
if (window.matchMedia("(orientation: portrait)").matches) {
if (viewWidth > viewHeight) {
viewHeight = viewWidth - chromeFootPrint;
viewWidth = tmpHeight + chromeFootPrint;
}
} else {
if (viewWidth < viewHeight) {
viewHeight = viewWidth - chromeFootPrint;
viewWidth = tmpHeight + chromeFootPrint;
}
}
var dimTarget = logScroll;
var offsetTop = dimTarget.offsetTop + dimTarget.clientTop;
var offsetLeft = dimTarget.offsetLeft + dimTarget.clientLeft;
while (dimTarget = dimTarget.offsetParent) {
offsetTop += dimTarget.offsetTop + dimTarget.clientTop;
offsetLeft += dimTarget.offsetLeft + dimTarget.clientLeft;
}
logScrollHeight = viewHeight - (offsetTop + fireBreak);
logScroll.style.height = logScrollHeight + "px";
logScroll.style.width = getStyle(contentDiv).width;
logWindow.style.height = logScroll.style.height;
logWindow.style.width = logScroll.style.width;
logWindow.scrollTop = logWindow.scrollHeight - logScrollHeight;
contentDiv.style.visibility = "visible"; // Now we're presentable
}
and this is the fire-break calculation: -
var outerStyle = getStyle(wholeScreen);
fireBreak = Number(outerStyle.paddingBottom.match("[0-9.]*"))
+ Number(outerStyle.borderBottomWidth.match("[0-9.]*"))
;
resizeContent();
EDIT 1: Ok, let me re-phrase the question: - How to I find out the height of my DIVs content with: -
width: 250px;
border: 3px solid green;
padding: 0.5em;
box-sizing: border-box;
I am currently having to do this: -
logScrollHeight = viewHeight -
(offsetTop + Number(getStyle(headerDiv).paddingBottom.match("[0-9.]*")));
Original question: -
This is bound to be a duplicate but after nearly an hour of looking I have found many similar/identical questions but no real answer :-(
Why aren't the boundryWith and padding deducted from height?
Thankfully the boundryBottomWidth and PaddingBottom return have been converted to pixels (including the "px" string sadly) but doesn't the standard say that the usable height should be returned?
To get the height of an element, you don't use getComputedStyle.
getComputedStyle should only be used to get the parsed values that are currently applied from different style-sheets. In other words, you can see it as a live style-sheet, only targeted to a single element, with standardized units.
But in no way it should be used to get the current height or width of an element. Too many factors may interfere with the set value, and an element can even have an height without having any CSS height rule set.
So yes... when the height CSS rule is set to auto, you will get the computed value, which may coincide with the real height of the element, but it also may not be so.
So in order to get the displayed height of an element, without the border and padding, we will need to do some calculations ourself.
Element#getBoundingClientRect() will give us the real displayed dimensions of our element, transformations included. .offsetHeight will give us the untransformed height including the border-box, and .clientHeight will give us the untransformed height with the padding-box.
This means that we will first have to get all the border and padding computed values, then get the current scale of our element, and finally remove the scaled padding + border boxes from the values we get with getBoundingClientRect.
Here is an example, which will draw a new rectangle div atop the element's bounding-box without padding and border boxes.
let marker;
scale.onclick = e => {
element.classList.toggle('scaled');
drawRect();
}
boxSizing.onclick = e => {
element.classList.toggle('boxSized');
drawRect();
}
function drawRect() {
// remove previous marker if any
if (marker && marker.parentNode) {
marker.remove();
marker = null;
}
// first get the border and padding values
let computed = getComputedStyle(element);
let borderLeft = parseFloat(computed.borderLeftWidth);
let borderWidth = borderLeft + parseFloat(computed.borderRightWidth);
let borderTop = parseFloat(computed.borderTopWidth);
let borderHeight = borderTop + parseFloat(computed.borderBottomWidth);
let paddingLeft = parseFloat(computed.paddingLeft);
let paddingWidth = paddingLeft + parseFloat(computed.paddingRight)
let paddingTop = parseFloat(computed.paddingTop);
let paddingHeight = paddingTop + parseFloat(computed.paddingBottom);
// get the current bounding rect, including the border-box
let rect = element.getBoundingClientRect();
// we need to get the current scale since the computed values don't know about it...
let scale = 1 / (element.offsetHeight / rect.height);
// the real displayed height and width without border nor padding
let height = rect.height - ((borderHeight + paddingHeight) * scale);
let width = rect.width - ((borderWidth + paddingWidth) * scale);
// create our rectangle
marker = document.createElement('div');
marker.classList.add('marker');
marker.style.height = height + 'px';
marker.style.width = width + 'px';
// we need to scale border + padding again
marker.style.top = (rect.top + (borderTop + paddingTop) * scale) + 'px';
marker.style.left = (rect.left + (borderLeft + paddingLeft) * scale) + 'px';
document.body.append(marker);
}
#element {
width: 250px;
border: 0.5em solid green;
padding: 0.5em;
margin-top: 12px;
}
#element.scaled {
transform: scale(2);
transform-origin: top left;
}
#element.boxSized {
box-sizing: border-box;
}
.marker {
position: fixed;
width: 3px;
background: rgba(0, 0, 0, .3)
}
<label>scale
<input id="scale" type="checkbox">
</label>
<label>box-sizing
<input id="boxSizing" type="checkbox">
</label>
<div id="element">
Hello
<br> world
</div>
when you set box-sizing as border-box:
The width and height properties include the content, the padding and border, but not the margin
So when you use getComputedStyle to get a element's height, of course it includes the height of padding and border.
you can have a look at box-sizing property and css box model
I'm coding a very tiny small feature, but I'm having problems with the scroll. I need to do a zoom of a div scaling with css:
transform: scale(X,Y)
But my problem is that I don't have a correct left and top scroll in the parent div. I need to know how to calculate the new left and top each time the user press the button "More zoom", I could use translate css property if it is mandatory.
I can use jQuery, but I think this is just a math problem :)
One detail: I need that the image grow from the center.
Picture:
Here is the fiddle:
Fiddle example
i believe you need to mind transform-origin too:
// get element references
var foo = document.querySelector('#foo');
var bar = document.querySelector('#bar');
// fit bar into foo
// the third options argument is optional, see the README for defaults
// https://github.com/soulwire/fit.js
var zoom = 1;
var trans = 50;
var moreZoom = document.querySelector('#moreZoom');
moreZoom.onclick = function(e){
console.log(foo);
bar.style.transform = 'scale(' + (zoom + 0.1) + ',' + (zoom + 0.1) + ')';
zoom = (zoom + 0.1);
bar.style.transformOrigin = (50 / zoom) +'px ' +(50 / zoom )+'px';
}
#foo {
background: #36D7B7;
height: 200px;
width: 400px;
padding: 50px;
overflow: auto;
}
#bar {
background-image: url('http://www.space.com/images/i/000/028/001/original/wing-small-magellanic-cloud-galaxy-1920.jpg?interpolation=lanczos-none&fit=around%7C1440:900&crop=1440:900;*,*');
background-size:cover;
height: 100%;
transform:scale(1);
width: 100%;
}
<script src="https://rawgithub.com/soulwire/fit.js/master/fit.js"></script>
<button id="moreZoom">
More Zoom
</button>
<div id="foo">
<div
http://jsfiddle.net/as20h6t4/5/
I am trying to slide image from left to right and after a set point it should again slide in reverse direction. This is my code somehow its not working as i am going wrong somewhere in the if statement.
(function($) {
var x = 0;
var y = 0;
//cache a reference to the banner
var banner = $("#banner");
// set initial banner background position
banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
// scroll up background position every 90 milliseconds
window.setInterval(function() {
banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
x++;
//x--;
//if you need to scroll image horizontally -
// uncomment x and comment y
}, 90);
if ($(banner.offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
})(jQuery);
div#banner {
width: 960px;
height: 200px;
margin: auto;
background: url(http://cdn-careers.sstatic.net/careers/gethired/img/companypageadfallback-leaderboard-2.png?v=59b591051ad7) no-repeat 0 0;
}
div#banner p {
font: 15px Arial, Helvetica, sans-serif;
color: white;
position: relative;
left: 20px;
top: 120px;
width: 305px;
padding: 20px;
background: black;
text-align: center;
text-transform: uppercase;
letter-spacing: 20px;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner"></div>
Firstly, you are using a IIFE (Immediately Invoked Function Expression) instead of a DOM ready handler. This code will only work if placed after the elements it references.
Use this shortcut for DOM ready that also provides a locally scoped $
jQuery(function ($) {...});
You also have a missing closing paren (or really a redundant $( as it is already a jQuery object):
JSFiddle: http://jsfiddle.net/g0gn4osy/7/
You also need to have a delta value that changes the direction when you hit a bound value. I sped up your timing to show this:
jQuery(function ($) {
var delta = 1;
var y = 0;
//cache a reference to the banner
var $banner = $("#banner");
// set initial banner background position
$banner.css('background-position', '0px' + ' ' + y + 'px');
// scroll up background position every 90 milliseconds
window.setInterval(function () {
var position = parseInt($banner.css('background-position'));
if (position >= 40 || position < 0) {
delta = -delta;
}
position += delta;
$banner.css("background-position", position + 'px' + ' ' + y + 'px');
}, 10);
});
Notes:
You also had backgroundPosition instead of background-position for the CSS property. I prefer to use the values that match the css properties (personal choice only for maintenance).
To avoid the redundant $() issue, I recommend you prefix jQuery variables with $. e.g. $banner in this case. Then it becomes obvious you are dealing with a jQuery object.
I tend to use the current position of an element, rather than keep a global var running. This allows for external influences to change the position and still work. Have removed x and just use position.
Inspired and modelled on Gone Coding's answer.
I have expanded his example to take into account the image width and the view pane DIV width.
It now scrolls to image end and then back. You never scroll off the canvas or past a visible part of the image. It doesn't jerk or rock, just switches direction.
With awareness of the viewing box width you can easily adjust the width of div#banner to fit the display space and the code adjusts. Just remember to set the background image width imgW var.
I have also added:
Visual indicator for testing with a current position and scroll direction. (With -1 is scrolling left, +1 is scrolling right),
Image start position in px. (A minus number or Zero. With 0 is start image at left, Minus number is start image part way through i.e image pre-scrolled left)
Image start vertical position in px (to vertically pull image up/down. Useful if view pane height shorter than image height and you want to tweak what is seen)
Things to do:
Change image URL (background: url(IMAGENAMEHERE) no-repeat 0 0;)
Insert image width (var imgW = #PIXELWIDTH#;)
Play with WIDTH: and HEIGHT: of view pane (div#banner)
Enjoy.
Fiddle
Have a play http://jsfiddle.net/Lm5yk46h/
Image credit Mark Higgins | Dreamstime.com Image source for purchase
Javascript
jQuery(function ($) {
var delta = 1;
var imgW = 3000;//width of image px
var imgY = 0;//to shift image view vertically px (Minus or zero)
//cache ref to #banner
var $banner = $("#banner");
var viewpaneW = $banner.width();
var endpos = (imgW - viewpaneW);
var startpos = 0;//0 or negative number
// set initial banner background position
$banner.css('background-position', startpos + 'px' + ' ' + imgY + 'px');
// scroll background position every 20ms
window.setInterval(function () {
var position = parseInt($banner.css('background-position'));
// minus is left, plus is right
if (position >= 0 ) delta = -delta;//go left
if (position < (-1*endpos)) delta = (-1*delta);//go right
position += delta;//increment posn
$banner.css("background-position", position + 'px' + ' ' + imgY + 'px');
$("#indicator").text('Posn:' + position + ' | direction: ' + delta);
}, 20);
});
CSS
div#canvas {
background-color: #999;
width: 100%;
height: 400px;
margin:0;padding:10px;
}
div#banner {
width: 460px;
height: 300px;
margin: 10px;
background: url(https://digido.net/eg/newcastle-beach-3000x300.jpg) no-repeat 0 0;
}
div#banner p {
font: 13px Arial, Helvetica, sans-serif;
color: white;
position: relative;
left: 0;
top: 310px;
width: 99%;
padding: 10px;
background: black;
text-align: center;
text-transform: uppercase;
letter-spacing: 8px;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
HTML
<div id="canvas">
<div id="banner">
<p id="indicator">Hit run</p>
</div>
</div>
Just put the if condition inside the setInterval. And check the syntax error. The if doesn't have a closing }:
// scroll up background position every 90 milliseconds
window.setInterval(function() {
banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
x++;
//x--;
if (banner.offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
}, 90);
Your "if" should be like this:
if ($(banner).offset().left > 40) {
banner.css("backgroundPosition", "0px 0px ");
}
https://jsfiddle.net/wc4b2g97/
your if should be inserted inside your setInterval handler, so it would get evaluated every 90 milliseconds (thank you for correcting me).
Actually, your if is evaluted only the first time, when your javascript file is parse.
Add it into your setInterval and it should work as expected
I'm getting absolutely positioned rotated elements position with jQuery .position() method, then setting position-related attributes (top, left) with jQuery .css(pos), where pos is the data returned by .position(). I think it'll leave the element in it's place, but elements position is changing.
How can I use set rotated elements position, so that it'll be placed as expected? Maybe there is a coefficient depended on angle that changes position?
I'm testing in Google Chrome v.9, Windows XP.
HTML
<div id="container">
<div id="element">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcS0Fawya9MVMez80ZusMVtk_4-ScKCIy6J_fg84oZ37GzKaJXU74Ma0vENc"/>
</div>
</div>
CSS
#container {
position: relative;
border: 1px solid #999;
padding: 5px;
height: 300px;
width:300px;
}
#element {
position: absolute;
top:50px;
left: 60px;
width: auto;
border: 1px solid #999;
padding: 5px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
}
JS
$(document).ready(function(){
var $el = $('#element'),
// getting position
pos = $el.position();
alert(pos.left + '/' + pos.top);
// alerts 37/11
// setting css position attributes equal to pos
$el.css(pos);
// re-getting position
pos = $el.position();
alert(pos.left + '/' + pos.top);
// alerts 14/-28
});
View it http://jsfiddle.net/Antaranian/2gVL4/
// Needed to read the "real" position
$.fn.adjustedPosition = function() {
var p = $(this).position();
return {
left: p.left - this.data('dx'),
top: p.top - this.data('dy')
}
};
$(function() {
var img = $('img'),
pos;
// Calculate the delta
img.each(function() {
var po = $(this).position(), // original position
pr = $(this).addClass('rot').position(); // rotated position
$(this).data({
dx: pr.left - po.left, // delta X
dy: pr.top - po.top // delta Y
});
});
// Read the position
pos = img.adjustedPosition();
alert(pos.left + '/' + pos.top);
// Write the position
img.css(pos);
// Read the position again
pos = img.adjustedPosition();
alert(pos.left + '/' + pos.top);
});
Live demo: http://jsfiddle.net/2gVL4/4/
So what is going on here:
The CSS code that rotates the image is stored inside a special CSS class. I do this because I want to read the original position of the image (before rotating). Once I read that original position, I apply the .rot class, and then read the position again to calculate the difference (delta), which is stored inside the element's data().
Now, I can read the position via the custom method adjustedPosition (which is defined above). This method will read the position of the element and then subtract the delta values stored inside the data() of the element.
To write the position, just use the css(pos) method like normally.
Had similar problem. There is simple solution (not elegant, but working):
set current angle to 0
read X/Y position
revert angle back to its value
var temp = $(this).position();
temp.angle = getRotationDegrees( $(this) ); // remember current angle
rotateObject($(this), 0); // set angle to 0
temp.left = Math.round($(this).position().left); // proper value
temp.top = Math.round($(this).position().top); // proper value
// revert back the angle
rotateObject($(this), temp.angle);
Used functions:
function rotateObject(obj, angle) {
obj.css({ '-webkit-transform': 'rotate(' + angle + 'deg)'});
obj.css({ '-moz-transform': 'rotate(' + angle + 'deg)'});
obj.css({ '-ms-transform': 'rotate(' + angle + 'deg)'});
obj.css({ 'msTransform': 'rotate(' + angle + 'deg)'});
obj.css({ '-o-transform': 'rotate(' + angle + 'deg)'});
obj.css({ '-sand-transform': 'rotate(' + angle + 'deg)'});
obj.css({ 'transform': 'rotate(' + angle + 'deg)'});
}
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if(matrix !== 'none') {
var tr;
if (tr = matrix.match('matrix\\((.*)\\)')) {
tr = tr[1].split(',');
if(typeof tr[0] != 'undefined' && typeof tr[1] != 'undefined') {
var angle = Math.round(Math.atan2(tr[1], tr[0]) * (180/Math.PI));
}else{
var angle = 0;
}
}else if(tr = matrix.match('rotate\\((.*)deg\\)')){
var angle = parseInt(tr[1]);
}
} else { var angle = 0; }
return (angle < 0) ? angle + 360 : angle;
}