Getting the updated div offset after applying a CSS class to it - javascript

I'm trying to implement an effect where an image (it can be of varying sizes) zooms on hover with a border appears around it. The non-zoomed image is limited to a maximum size of 250px and the zoomed to 550px.
I do this by applying a class to the div on mouseenter and remove it on mouseleave. This works well enough, but the problem is that I want to detect if the div goes partly off-screen. To do this I need the offset of the transformed div:
$(document).ready(function () {
$('.image-container').on('mouseenter', function () {
var y = $(this).offset().top,
x = $(this).offset().left;
console.log('old', x, y);
$(this).addClass('image-hover');
y = $(this).offset().top;
x = $(this).offset().left;
console.log('new', x, y);
});
$('.image-container').on('mouseleave', function () {
$(this).removeClass('image-hover');
});
});
If you look at the jsfiddle below, I get the old offsets after adding the class.
http://jsfiddle.net/6JZCW/14/
So, how to get the updated offsets? Is there a better way of doing what I want to achieve?

you are trying to get offset of your $('.image-container'), but its padding never change, you change only the padding of '.image-block' so when you console.log do this
$('.image-block').offset().top;
$('.image-block').offset().top;

Related

JavaScript(Canvas): How to update the pointer's position inside the animation frame and NOT inside the event listener? [duplicate]

Is it possible to get the mouse position with JavaScript after page loads without any mouse movement event (without moving the mouse)?
Real answer: No, it's not possible.
OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a> elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those <a> elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million <a> elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.
N.B. DON'T DO THIS.
Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.
Old answer:
You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:
var x = null;
var y = null;
document.addEventListener('mousemove', onMouseUpdate, false);
document.addEventListener('mouseenter', onMouseUpdate, false);
function onMouseUpdate(e) {
x = e.pageX;
y = e.pageY;
console.log(x, y);
}
function getMouseX() {
return x;
}
function getMouseY() {
return y;
}
You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.
What you can do is create variables for the x and y coordinates of your cursor, update them whenever the mouse moves and call a function on an interval to do what you need with the stored position.
The downside to this of course is that at least one initial movement of the mouse is required to have it work. As long as the cursor updates its position at least once, we are able to find its position regardless of whether it moves again.
var cursor_x = -1;
var cursor_y = -1;
document.onmousemove = function(event)
{
cursor_x = event.pageX;
cursor_y = event.pageY;
}
setInterval(check_cursor, 1000);
function check_cursor(){console.log('Cursor at: '+cursor_x+', '+cursor_y);}
The preceding code updates once a second with a message of where your cursor is.
#Tim Down's answer is not performant if you render 2,000 x 2,000 <a> elements:
OK, I have just thought of a way. Overlay your page with a div that
covers the whole document. Inside that, create (say) 2,000 x 2,000
elements (so that the :hover pseudo-class will work in IE 6, see),
each 1 pixel in size. Create a CSS :hover rule for those elements
that changes a property (let's say font-family). In your load handler,
cycle through each of the 4 million elements, checking
currentStyle / getComputedStyle() until you find the one with the
hover font. Extrapolate back from this element to get the co-ordinates
within the document.
N.B. DON'T DO THIS.
But you don't have to render 4 million elements at once, instead use binary search. Just use 4 <a> elements instead:
Step 1: Consider the whole screen as the starting search area
Step 2: Split the search area into 2 x 2 = 4 rectangle <a> elements
Step 3: Using the getComputedStyle() function determine in which rectangle mouse hovers
Step 4: Reduce the search area to that rectangle and repeat from step 2.
This way you would need to repeat these steps max 11 times, considering your screen is not wider than 2048px.
So you will generate max 11 x 4 = 44 <a> elements.
If you don't need to determine the mouse position exactly to a pixel, but say 10px precision is OK. You would repeat the steps at most 8 times, so you would need to draw max 8 x 4 = 32 <a> elements.
Also generating and then destroying the <a> elements is not performat as DOM is generally slow. Instead, you can just reuse the initial 4 <a> elements and just adjust their top, left, width and height as you loop through steps.
Now, creating 4 <a> is an overkill as well. Instead, you can reuse the same one <a> element for when testing for getComputedStyle() in each rectangle. So, instead of splitting the search area into 2 x 2 <a> elements just reuse a single <a> element by moving it with top and left style properties.
So, all you need is a single <a> element change its width and height max 11 times, and change its top and left max 44 times and you will have the exact mouse position.
You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.
For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...
Here's my solution. It exports window.currentMouseX and window.currentMouseY properties you can use anywhere. It uses the position of a hovered element (if any) initially and afterwards listens to mouse movements to set the correct values.
(function () {
window.currentMouseX = 0;
window.currentMouseY = 0;
// Guess the initial mouse position approximately if possible:
var hoveredElement = document.querySelectorAll(':hover');
hoveredElement = hoveredElement[hoveredElement.length - 1]; // Get the most specific hovered element
if (hoveredElement != null) {
var rect = hoveredElement.getBoundingClientRect();
// Set the values from hovered element's position
window.currentMouseX = window.scrollX + rect.x;
window.currentMouseY = window.scrollY + rect.y;
}
// Listen for mouse movements to set the correct values
window.addEventListener('mousemove', function (e) {
window.currentMouseX = e.pageX;
window.currentMouseY = e.pageY;
}, /*useCapture=*/true);
}())
Composr CMS Source: https://github.com/ocproducts/composr/commit/a851c19f925be20bc16bfe016be42924989f262e#diff-b162dc9c35a97618a96748639ff41251R1202
The most simple solution but not 100% accurate
$(':hover').last().offset()
Result: {top: 148, left: 62.5}
The result depend on the nearest element size and return undefined when user switched the tab
Yes, It's possible.
If you add "mouseover" event to the document it will fire instantly and you can get the mouse position, of course if mouse pointer was over the document.
document.addEventListener('mouseover', setInitialMousePos, false);
function setInitialMousePos( event ) {
console.log( event.clientX, event.clientY);
document.removeEventListener('mouseover', setInitialMousePos, false);
}
Previously it was possible to read mouse position through window.event but it's deprecated now.
var x = 0;
var y = 0;
document.addEventListener('mousemove', onMouseMove, false)
function onMouseMove(e){
x = e.clientX;
y = e.clientY;
}
function getMouseX() {
return x;
}
function getMouseY() {
return y;
}
I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.
jsfiddle.net/5XzeE/4/
You do not have to move the mouse to get the cursor's location. The location is also reported on events other than mousemove. Here's a click-event as an example:
document.body.addEventListener('click',function(e)
{
console.log("cursor-location: " + e.clientX + ',' + e.clientY);
});
Riffing on #SuperNova's answer, here's an approach using ES6 classes that keeps the context for this correct in your callback:
class Mouse {
constructor() {
this.x = 0;
this.y = 0;
this.callbacks = {
mouseenter: [],
mousemove: [],
};
}
get xPos() {
return this.x;
}
get yPos() {
return this.y;
}
get position() {
return `${this.x},${this.y}`;
}
addListener(type, callback) {
document.addEventListener(type, this); // Pass `this` as the second arg to keep the context correct
this.callbacks[type].push(callback);
}
// `handleEvent` is part of the browser's `EventListener` API.
// https://developer.mozilla.org/en-US/docs/Web/API/EventListener/handleEvent
handleEvent(event) {
const isMousemove = event.type === 'mousemove';
const isMouseenter = event.type === 'mouseenter';
if (isMousemove || isMouseenter) {
this.x = event.pageX;
this.y = event.pageY;
}
this.callbacks[event.type].forEach((callback) => {
callback();
});
}
}
const mouse = new Mouse();
mouse.addListener('mouseenter', () => console.log('mouseenter', mouse.position));
mouse.addListener('mousemove', () => console.log('mousemove A', mouse.position));
mouse.addListener('mousemove', () => console.log('mousemove B', mouse.position));
Not mouse position, but, if you're looking for current cursor postion (for use cases like getting last typed character etc) then, below snippet works fine.
This will give you the cursor index related to text content.
window.getSelection().getRangeAt(0).startOffset
I envision that maybe you have a parent page with a timer and after a certain amount of time or a task is completed, you forward the user to a new page. Now you want the cursor position, and because they are waiting, they aren't necessarily touching the mouse. So track the mouse on the parent page using standard events and pass the last value to the new page in a get or a post variable.
You can use JHarding's code on your parent page so that the latest position is always available in a global variable:
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
This won't help users that navigate to this page by means other than your parent page.
I think i may have a reasonable solution with out counting divs and pixels..lol
Simply use animation frame or a time interval of a function. you will still need a mouse event one time though just to initiate, but technically you position this where ever you like.
Essentially we are tracking a dummy div at all times with out mouse movement.
// create a div(#mydiv) 1px by 1px set opacity to 0 & position:absolute;
Below is the logic..
var x,y;
$('body').mousemove(function( e ) {
var x = e.clientX - (window.innerWidth / 2);
var y = e.clientY - (window.innerHeight / 2);
}
function looping (){
/* track my div position 60 x 60 seconds!
with out the mouse after initiation you can still track the dummy div.x & y
mouse doesn't need to move.*/
$('#mydiv').x = x; // css transform x and y to follow
$('#mydiv)'.y = y;
console.log(#mydiv.x etc)
requestAnimationFrame( looping , frame speed here);
}

Fit image to width using fixed positioned button

I have a page with the following functionality: there is a large image that generates scoll (both horizontally and vertically) and a button in a fixed position (it remains in the top left corner, even with scroll) that, when clicked, fits the image to the client width.
Since position: fixed is not supported in Internet Explorer 8, I used a workaround - this is the function:
function setFixedPosition(jqueryWrapper, pixelsFromTop, pixelsFromLeft) {
jqueryWrapper.css('position', 'absolute');
var setOffsets = function() {
jqueryWrapper.css("top", (($(window).scrollTop() + pixelsFromTop) + "px"));
jqueryWrapper.css("left", (($(window).scrollLeft() + pixelsFromLeft) + "px"));
};
setOffsets();
$(window).scroll(function() {
setOffsets();
});
}
setFixedPosition($('#zoomFitButton'), 15, 15);
This is the button's action:
$('#zoomFitButton').click(function() {
$('img.preview').css('width', '100%');
});
The button remains fixed both in Firefox 13 and IE8.
But, under IE8, if I am scrolling somewhere, then I click the button, the button moves to a "strange" position:
If I scroll vertically, then click, it puts the button in the lower-left corner;
If I scroll horizontally, then click, it puts the button in the upper-right corner;
If I scroll both ways, then click, it puts the button somewhere in the center.
In Firefox, the button always remains in the upper-left corner (the place where I expect it to be), even after I click the fit to width button.
Here is a test page.
Is my code OK for this functionality (in principle), or I need to add something to the fit to width action (to fix my button positioning); or there is something wrong with IE (and I need a workaround - if so, any suggestions?)?
Thanks.
I found a solution that works in IE6 also.
I think the problem has something to do with IE not updating the scrollTop and scrollLeft positions after the document is resized.
So, after I resize the picture, I have to scroll to the upper-left corner (scrollTop(0) and scrollLeft(0)).
Unfortunately, if I have a large picture that needs vertical scrolling even when it's fit to width, the workaround brings me to the top of the page. So I added code to bring me back proportionally to the aproximate position I was before. I wrapped the logic in a more generic function:
function doSomethingThatAffectsScrollPosition(affectingScrollPositionFunction) {
var oldDocumentWidth = $(document).width();
var oldScrollFromLeft = $(window).scrollLeft();
var oldDocumentHeight = $(document).height();
var oldScrollFromTop = $(window).scrollTop();
affectingScrollPositionFunction();
var newDocumentWidth = $(document).width();
var widthRatio = (newDocumentWidth / oldDocumentWidth);
var newScrollFromLeft = (oldScrollFromLeft * widthRatio);
var newDocumentHeight = $(document).height();
var heightRatio = (newDocumentHeight / oldDocumentHeight);
var newScrollFromTop = (oldScrollFromTop * heightRatio);
$(window).scrollLeft(0); // Needed for button repositioning
$(window).scrollLeft(newScrollFromLeft);
$(window).scrollTop(0); // Needed for button repositioning
$(window).scrollTop(newScrollFromTop);
}
And I used the function in the fit to width button's action:
$('#zoomFitButton').click(function() {
doSomethingThatAffectsScrollPosition(function() {
$('img.preview').css('width', '100%');
});
});
Here is a test page.

Coordinates of HTML elements

I am going to create a selection 'lasso' that the user can use to select portions of a table. I figured that positioning a div over the region is far easier than trying to manipulate the cell borders.
If you don't understand what I mean, open up a spread sheet and drag over a region. I want the div to align perfectly with the cell borders.
I have a very good idea of how to do this, but how would I get the (x,y) coordinates (screen position) of a table cell (td)?
Use .offset() along with .height() and .width() if necessary.
var td = $(someTDReference);
var pos = td.offset();
pos.bottom = pos.top + td.height();
pos.right = pos.left + td.width();
// pos now contains top, left, bottom, and right in pixels
Edit: Not .position(), use .offset(). Updated above.
Edit: Changed pos.width() to td.width()
Hey you should be able to do it like this (jsFiddle): http://jsfiddle.net/jackrugile/YKHkX/
$('td').hover(function(){
var xPos = Math.floor($(this).offset().left);
var yPos = Math.floor($(this).offset().top);
});
The Math.floor gets rid of the crazy decimals and makes it easier to work with in my opinion. Hope that helps!
you can use pageX and pageY to trackdown the mouse cursor x , y
$("#your_div").mouseover(function(e))
{
x = e.pageX;
y = e.pageY;
}
you can set the div border to highlight the div on mouseover simply by
$("#your_div").css("border","1px solid black");
this will kinda show current div selectable effect...
that if if the div is
position:fixed and then you can read its left and top property
hope that helps you
For those who doesn't want to use jquery:
var coordinates = td.getBoundingClientRect();
console.log(coordinates.left, coordinates.top, coordinates.right, coordinates.bottom);

How to get the mouse position without events (without moving the mouse)?

Is it possible to get the mouse position with JavaScript after page loads without any mouse movement event (without moving the mouse)?
Real answer: No, it's not possible.
OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a> elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those <a> elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million <a> elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.
N.B. DON'T DO THIS.
Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.
Old answer:
You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:
var x = null;
var y = null;
document.addEventListener('mousemove', onMouseUpdate, false);
document.addEventListener('mouseenter', onMouseUpdate, false);
function onMouseUpdate(e) {
x = e.pageX;
y = e.pageY;
console.log(x, y);
}
function getMouseX() {
return x;
}
function getMouseY() {
return y;
}
You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.
What you can do is create variables for the x and y coordinates of your cursor, update them whenever the mouse moves and call a function on an interval to do what you need with the stored position.
The downside to this of course is that at least one initial movement of the mouse is required to have it work. As long as the cursor updates its position at least once, we are able to find its position regardless of whether it moves again.
var cursor_x = -1;
var cursor_y = -1;
document.onmousemove = function(event)
{
cursor_x = event.pageX;
cursor_y = event.pageY;
}
setInterval(check_cursor, 1000);
function check_cursor(){console.log('Cursor at: '+cursor_x+', '+cursor_y);}
The preceding code updates once a second with a message of where your cursor is.
#Tim Down's answer is not performant if you render 2,000 x 2,000 <a> elements:
OK, I have just thought of a way. Overlay your page with a div that
covers the whole document. Inside that, create (say) 2,000 x 2,000
elements (so that the :hover pseudo-class will work in IE 6, see),
each 1 pixel in size. Create a CSS :hover rule for those elements
that changes a property (let's say font-family). In your load handler,
cycle through each of the 4 million elements, checking
currentStyle / getComputedStyle() until you find the one with the
hover font. Extrapolate back from this element to get the co-ordinates
within the document.
N.B. DON'T DO THIS.
But you don't have to render 4 million elements at once, instead use binary search. Just use 4 <a> elements instead:
Step 1: Consider the whole screen as the starting search area
Step 2: Split the search area into 2 x 2 = 4 rectangle <a> elements
Step 3: Using the getComputedStyle() function determine in which rectangle mouse hovers
Step 4: Reduce the search area to that rectangle and repeat from step 2.
This way you would need to repeat these steps max 11 times, considering your screen is not wider than 2048px.
So you will generate max 11 x 4 = 44 <a> elements.
If you don't need to determine the mouse position exactly to a pixel, but say 10px precision is OK. You would repeat the steps at most 8 times, so you would need to draw max 8 x 4 = 32 <a> elements.
Also generating and then destroying the <a> elements is not performat as DOM is generally slow. Instead, you can just reuse the initial 4 <a> elements and just adjust their top, left, width and height as you loop through steps.
Now, creating 4 <a> is an overkill as well. Instead, you can reuse the same one <a> element for when testing for getComputedStyle() in each rectangle. So, instead of splitting the search area into 2 x 2 <a> elements just reuse a single <a> element by moving it with top and left style properties.
So, all you need is a single <a> element change its width and height max 11 times, and change its top and left max 44 times and you will have the exact mouse position.
You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.
For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...
Here's my solution. It exports window.currentMouseX and window.currentMouseY properties you can use anywhere. It uses the position of a hovered element (if any) initially and afterwards listens to mouse movements to set the correct values.
(function () {
window.currentMouseX = 0;
window.currentMouseY = 0;
// Guess the initial mouse position approximately if possible:
var hoveredElement = document.querySelectorAll(':hover');
hoveredElement = hoveredElement[hoveredElement.length - 1]; // Get the most specific hovered element
if (hoveredElement != null) {
var rect = hoveredElement.getBoundingClientRect();
// Set the values from hovered element's position
window.currentMouseX = window.scrollX + rect.x;
window.currentMouseY = window.scrollY + rect.y;
}
// Listen for mouse movements to set the correct values
window.addEventListener('mousemove', function (e) {
window.currentMouseX = e.pageX;
window.currentMouseY = e.pageY;
}, /*useCapture=*/true);
}())
Composr CMS Source: https://github.com/ocproducts/composr/commit/a851c19f925be20bc16bfe016be42924989f262e#diff-b162dc9c35a97618a96748639ff41251R1202
The most simple solution but not 100% accurate
$(':hover').last().offset()
Result: {top: 148, left: 62.5}
The result depend on the nearest element size and return undefined when user switched the tab
Yes, It's possible.
If you add "mouseover" event to the document it will fire instantly and you can get the mouse position, of course if mouse pointer was over the document.
document.addEventListener('mouseover', setInitialMousePos, false);
function setInitialMousePos( event ) {
console.log( event.clientX, event.clientY);
document.removeEventListener('mouseover', setInitialMousePos, false);
}
Previously it was possible to read mouse position through window.event but it's deprecated now.
var x = 0;
var y = 0;
document.addEventListener('mousemove', onMouseMove, false)
function onMouseMove(e){
x = e.clientX;
y = e.clientY;
}
function getMouseX() {
return x;
}
function getMouseY() {
return y;
}
I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.
jsfiddle.net/5XzeE/4/
You do not have to move the mouse to get the cursor's location. The location is also reported on events other than mousemove. Here's a click-event as an example:
document.body.addEventListener('click',function(e)
{
console.log("cursor-location: " + e.clientX + ',' + e.clientY);
});
Riffing on #SuperNova's answer, here's an approach using ES6 classes that keeps the context for this correct in your callback:
class Mouse {
constructor() {
this.x = 0;
this.y = 0;
this.callbacks = {
mouseenter: [],
mousemove: [],
};
}
get xPos() {
return this.x;
}
get yPos() {
return this.y;
}
get position() {
return `${this.x},${this.y}`;
}
addListener(type, callback) {
document.addEventListener(type, this); // Pass `this` as the second arg to keep the context correct
this.callbacks[type].push(callback);
}
// `handleEvent` is part of the browser's `EventListener` API.
// https://developer.mozilla.org/en-US/docs/Web/API/EventListener/handleEvent
handleEvent(event) {
const isMousemove = event.type === 'mousemove';
const isMouseenter = event.type === 'mouseenter';
if (isMousemove || isMouseenter) {
this.x = event.pageX;
this.y = event.pageY;
}
this.callbacks[event.type].forEach((callback) => {
callback();
});
}
}
const mouse = new Mouse();
mouse.addListener('mouseenter', () => console.log('mouseenter', mouse.position));
mouse.addListener('mousemove', () => console.log('mousemove A', mouse.position));
mouse.addListener('mousemove', () => console.log('mousemove B', mouse.position));
Not mouse position, but, if you're looking for current cursor postion (for use cases like getting last typed character etc) then, below snippet works fine.
This will give you the cursor index related to text content.
window.getSelection().getRangeAt(0).startOffset
I envision that maybe you have a parent page with a timer and after a certain amount of time or a task is completed, you forward the user to a new page. Now you want the cursor position, and because they are waiting, they aren't necessarily touching the mouse. So track the mouse on the parent page using standard events and pass the last value to the new page in a get or a post variable.
You can use JHarding's code on your parent page so that the latest position is always available in a global variable:
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
This won't help users that navigate to this page by means other than your parent page.
I think i may have a reasonable solution with out counting divs and pixels..lol
Simply use animation frame or a time interval of a function. you will still need a mouse event one time though just to initiate, but technically you position this where ever you like.
Essentially we are tracking a dummy div at all times with out mouse movement.
// create a div(#mydiv) 1px by 1px set opacity to 0 & position:absolute;
Below is the logic..
var x,y;
$('body').mousemove(function( e ) {
var x = e.clientX - (window.innerWidth / 2);
var y = e.clientY - (window.innerHeight / 2);
}
function looping (){
/* track my div position 60 x 60 seconds!
with out the mouse after initiation you can still track the dummy div.x & y
mouse doesn't need to move.*/
$('#mydiv').x = x; // css transform x and y to follow
$('#mydiv)'.y = y;
console.log(#mydiv.x etc)
requestAnimationFrame( looping , frame speed here);
}

set height div javascript

I'm adjusting the height of the box with no problems, now I would like to adjust the height of the box grabbing the top handle and adjust height but upwards. What would be a good way of doing this? thanks
(current downwards code)
var mY = event.clientY;
var originalHeight = parseInt(document.getElementById('somediv').style.height);
if(click == 1){ // down
var sY = event.clientY;
var finalHeight = originalHeight +sY-mY;
document.getElementById('somediv').style.height=finalHeight + 'px';
}else{ // up
resize upwards instead of downwards....
}
An element's position is defined by its top-left corner - you'll have to move it up at the same time as you extend it from the bottom.
Resizing a DIV "up" is not as easy as resizing it "down". The reason is that when you specify a HEIGHT, the DIV will expand "down" as its normal flow. The top left corner of the DIV will remain static.
Allowing the DIV to be resized "UP" will give you a lot of issues. In order to do this, you will need to set the HEIGHT, then the POSITION of the DIV to currentHeight - previousHeight. You will notice it will jitter a lot when doing this.
Also, anything above your DIV will need to be displayed accordingly.
You should look into jQuery and the jQuery Dimensions plugin.

Categories