Position change while zoom in - javascript

Here I tried to make simple zoom in and out functions on button click.
HTML
<input type="button" value ="-" onClick="zoom(0.9)"/>
<input type="button" value ="+" onClick="zoom(1.1)"/>
<div id="thediv">
<img id="pic" src="http://cdn1.iconfinder.com/data/icons/VistaICO_Toolbar-Icons/256/Zoom-in.png"/>
</div>
SCRIPT
var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
But the problem is, whenever I click the zoom-in function the image moves to the top corner of the page. I tried to solve this but no solution was effective.
Here is the BIN I am working on which may be useful to find my mistake.
And also another question: Is there a way to apply mousewheel to this function?
UPDATE
The problem of zoom has been changed. But now the mousewheel also done here but the problem is we can't give the maximum value for the mousewheel.
UPDATED BIN

img.style.marginLeft = -(img.width/2) + "px"; // you have negation sign here
img.style.marginTop = -(img.height/2) + "px"; // you have negation sign here
Change it TO :
img.style.marginLeft = (img.width/2) + "px";
img.style.marginTop = (img.height/2) + "px";
JS BIN LINK

Judging by your marginLeft and marginTop calculation, I guess that you want to zoom in and out of the image while preserving the center point.
So try this:
http://jsbin.com/itekek/4
Preserved an initial width and height value, and slightly modified the zoom limit value.
Edit:
http://jsbin.com/itekek/46
Added mouse wheel support.

See this : http://jsbin.com/itekek/14/edit
You have unstripped zoom plus Mousewheel here..
Update: To get elements by class name use function below:
function findElementByClass(matchClass) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if ((" " + elems[i].className + " ").indexOf(" " + matchClass + " ") > -1) {
return elems[i];
}
}
return null;
}
See sample

Related

Calculating positioning of the parent Div

Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation

3D div transformation resetting

I successfully created a div that the user can "rotate". It works perfectly, except that rotating on the X direction cancels/resets the existing rotation in Y direction and vise versa. Also the div is a draggable object from jQuery. How can I fix this so that transformations are not reset?
<script>
var degreesY = 0;
function rotateLeft() {
var degreesuseY = degreesY + 10;
document.getElementById("Notes").style["transform"]= "rotateY(" + degreesuseY + "deg)";
}
var degreesX = 0;
function rotateUp() {
var degreesuseX = degreesX + 10;
document.getElementById("Notes").style["transform"]= "rotateX(" + degreesuseX + "deg)";
}
</script>
<div id="draggable">
<div class="LeftRotate" onclick="rotateLeft();degreesY=degreesY+10"></div>
<div class="UpRotate" onclick="rotateUp();degreesX=degreesX+10"></div>
</div>
The problem is that when you set the transform property, you're rewriting the current value and erasing what you have so far. Try changing your code to work instead with a single rotate() function and set the transform property as follows:
var degreesX = 0;
var degreesY = 0;
function rotate(xAxis) { //Make xAxis a boolean
if (xAxis) {
degreesX+=10;
} else {
degreesY+=10;
}
document.getElementById("Notes").style["transform"] = "rotate(" + degreesX + "deg " + degreesY + "deg)";
}
I put a simple example (using jQuery) in this jsFiddle.
You could avoid using xAxis, if you want, by having the function determine whether the element clicked has class UpRotate or LeftRotate.

dynamically increasing height of div in javascript

I want to increase the height of the div tag on click of button. Every time a user clicks a button it should increase the height of that particular div tag, say by 200px or so..
HTML
<div id="controls">
<input type="button" onclick="incHeight()" id="btn" name="btn">
</div>
<div id="container" style="min-height:250px;"> </div>
The below script works properly
Javascript
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height = 250+'px';
}
</script>
But I want to do something like this, which is not working. The problem I think is the 'px' portion in the value. Anybody have any idea how to extract the INT portion of the value...
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height += 250;
}
</script>
The problem is how do I get the '250' portion of the height value neglecting the 'px' in javascript..
Try this:
function incHeight() {
var el = document.getElementById("container");
var height = el.offsetHeight;
var newHeight = height + 200;
el.style.height = newHeight + 'px';
}
Fiddle
Try something like
var container = document.getElementById('container');
container.style.height = (container.offsetHeight + 250) + "px";
In case offsetHeight is not working, try parsing the style.height for its numeric value instead.
var currentHeight = (container.style.height) ? (parseInt(container.style.height.match(/[0-9]+/)[0]) : container.offsetHeight;
Also, simply parseInt(container.style.height) might work
Try this:
getElementById('container').setAttribute("style","height:500px");
or
function resize(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
You can use a regular expression to only keep the numbers in the string:
var style = document.getElementById("container").style;
style.height = style.height.replace( /^\D+/g, '') + 'px';

Trouble changing css with javascript

I want to change the padding on my header so that it effectively is lowered onto the page. I have the following code which runs and does nothing:
function openPage() {
var i, el = document.getElementById('headbar');
for(i=0;i<30;i++) {
el.style.paddingTop = el.style.paddingTop + 1;
}
}
However, while trying to figure out why it wasn't working in the console I figured out that maybe it is because the padding must be written in pixels because the following works and changes the padding in the console:
document.getElementById('headbar').style.paddingTop='100px';
is there any way I could do this without Jquery and without having to make a substring and reconcatonating?
Try appending px to the variable
var fontSize = parseInt(el.style.paddingTop, 10);
el.style.paddingTop = ( (!isNaN(fontSize) : fontSize : 0) + 1) + 'px';
Pretty simple just do this:
for(i=0;i<30;i++) {
var px = (el.style.paddingTop + 1) + "px";
el.style.paddingTop = px;
}

Issue with Image movement on mousemove (in opposite direction)

I have to move an image using jQuery / Javascript exactly like this url
I have done similar to this using my own logic. But it gets cut for smaller / bigger image either at the top or at the bottom. Or It moves completely at the bottom and doesn't move completely at the top or vice-versa.
http://jsfiddle.net/N2k6M/
(Please move the horizontal scrollbar to view full image.)
Can anyone please suggest me / Fix my code here, so that my mousemove functionality works perfectly fine and upper / lower part of image moves properly.
I need a seamless movement of image just like in the original url.
HTML PART
<div id="oheight" style="z-index:1000;position:absolute;">123</div> , <div id="yheight" style="z-index:1000;position:absolute;">123</div>
<img id="avatar" src="http://chaikenclothing.com/wp-content/uploads/2012/05/11.jpg![enter image description here][2]" style="position:absolute;overflow:hidden;" />
JAVASCRIPT PART
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script lang="javascript">
var doc_height = $(document).height();
function updateAvatarPosition( e )
{
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.y);
var ywidth = e.x;
//avatar.style.left = e.x + "px";
if((yheight)<(doc_height)){
yheight*=2;
avatar.style.top = '-'+(yheight) + "px";
}
console.log(yheight);
$("#oheight").html(doc_height);
$("#yheight").html(yheight);
/*if((ywidth)<(doc_height/6)){
avatar.style.top = '-'+e.x + "px";
}*/
}
document.getElementById("avatar").onmousemove = updateAvatarPosition;
</script>
see http://jsfiddle.net/N2k6M/7/
function updateAvatarPosition( e )
{
var img_height = $('#avatar').height();
var window_height = $(window).height();
var factor = (img_height - window_height) / window_height;
if(factor > 1) {
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.clientY);
avatar.style.top = '-'+(yheight * factor) + "px";
}
}
#Felix's answer is great and works well, however it's doing more work than necessary. There are a few constants that do not need to be reassigned with every call. By setting these outside of the updateAvatarPosition function you can improve performance some.
var avatar = $('#avatar');
img_height = avatar.height(),
window_height = $(window).height();
function updateAvatarPosition( e )
{
var factor = (img_height - window_height) / window_height,
yheight = parseInt(e.clientY);
if (factor < 1) {
factor = 1;
}
avatar.css('top', -(yheight * factor));
}
avatar.on('mousemove', updateAvatarPosition);
​
Updated Fiddle
Avatar is referenced more than once so no need to traverse the DOM multiple times, especially multiple times within a constantly cycling event like mousemove. Make a variable reference to avatar outside of the function. The image_height and window_height are also constants and do not change, so there is no need to recalculate them every time as well. If there is the chance that they would change, reassignment should be handled by a resize event.
Would have replied/commented directly under #Felix's answer but apparently don't have enough influence yet. :-/
i think this is something you want
http://jsfiddle.net/N2k6M/6/
var doc_height = $(document).height();
function updateAvatarPosition( e )
{
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.clientY);
var ywidth = e.clientX;
if((yheight)<(doc_height)){
yheight*=2;
avatar.style.top = '-'+(yheight) + "px";
}
/*if((ywidth)<(doc_height/6)){
avatar.style.top = '-'+e.x + "px";
}*/
}
document.getElementById("avatar").onmousemove = updateAvatarPosition;​

Categories