Resize an html element using mouse - jQuery - javascript

I have container and I want to resize it with mouse using JavaScript.
the implementation uses mousedown ,mouseup, and mousemove events but I have slight problem when page is already scrolled before the mousedown is fired.
the whole page seems to scroll to position zero. How can i fix it so whether page is already scrolled or not the resize will work fine.
JS:
//resize div vertically or horizontal or both
$.fn.resizeMe = function(options){
var grippie = $(this),
options = $.extend({resizeMe:"",resize:"vertical"},options),
resizeMe = $(options.resizeMe);
grippie.on('mousedown',function(e){initialiseGrippieResize(e)});
function initialiseGrippieResize(e) {
$(window).on('mousemove',function(e){
startResizing(e);
resizeMe.css({opacity:.25});
}).on('mouseup',function(e){
stopResizing(e);
resizeMe.css({opacity:1});
});
}
//css objects
function cssOBJ(e,key){
var css = {
vertical:{height:(e.clientY - resizeMe.offset().top)},
horizontal : {width:(e.clientX - resizeMe.offset().left)},
both: {
height:(e.clientY - resizeMe.offset().top),
width: (e.clientX - resizeMe.offset().left)
}
};
//return objects
return css[key];
}
//Start Resizing
function startResizing(e) {
resizeMe.css(cssOBJ(e,options.resize));
}
function stopResizing(e) {
$(window).off('mousemove mouseup');
}
}
$('.grippie').resizeMe({resizeMe:"#pane",resize:'vertical'});
HTML:
<div id='main-container'>
<div id='pane' arial-lable='content-wrapper'>contents will go here</div>
<div class='grippie'></div>
</div>
CSS:
#pane{
resize: n-resize;
overflow: hidden;
border: 1px solid #d6d9dc;
padding:15px 20px;
min-height:50px;
}
#pane *{border:0px !important; background: #fff !important;}
.grippie {
background-position: center;
border: 1px solid #d6d9dc;
border-width: 0 1px 1px;
cursor: s-resize;
height: 9px;
overflow: hidden;
background-color: #eff0f1;
/*background-image: url('images/icons.png');*/
background-repeat: no-repeat;

In JavaScript
pageX, pageY, screenX, screenY, clientX, and clientY returns a number which indicates the number of physical “CSS pixels” a point is from the reference point. The event point is where the user moved the mouse, the reference point is a point in the upper left. These properties return the horizontal and vertical distance from that reference point.
but pageX or pageY returns a number which indicates the amount of page scrolled top or left.
so changing the clientX to pageX and clientY to pageY
solved the problem and now I can resize any element. :) :)
//css objects
function cssOBJ(e,key){
var css = {
vertical:{height:(e.pageY - resizeMe.offset().top)},
horizontal : {width:(e.pageX - resizeMe.offset().left)},
both: {
height:(e.pageY - resizeMe.offset().top),
width: (e.pageX - resizeMe.offset().left)
}
};
//return objects
return css[key];
}

Related

How to get hold of div on mousemove?

JSFiddle code
I am trying to get hold of div with blue lines when I move the mouse pointer within a distance of 20px from the div. I am able to get hold of the div with blue lines only when the mouse pointer is on that div. Basically, selecting a div using the mouser pointer is difficult as the div width is only 1px which cannot be changed.
I am executing the below code but still not able to catch hold of the div which is 20px away from either right or left of the mouse pointer.
Note:The div mentioned above indicated the div with blue lines and not the gray box.
//Div positions and their id has been added to map
var hmap = new Map();
hmap.set("hguide1",96);
hmap.set("hguide2",284);
hmap.set("hguide3",520);
var vmap = new Map();
vmap.set("vguide1", 96);
vmap.set("vguide2",384);
vmap.set("vguide3",720);
$(document).mousemove(function(e){
var mx = e.pageX, my = e.pageY;
//Catch hold of vertical div's
for (var [key, value] of vmap) {
var dist = value - mx;
if(dist >= -20 && dist <= 20){
$('.'+key).css({width: '10px', left:});
} else {
$('.'+key).css({width: '1px'});
}
}
//Catch hold of horizontal div's
for (var [key, value] of hmap) {
var dist = value - my;
if(dist >= -20 && dist <= 20){
$('.'+key).css({height: '10px'});
} else {
$('.'+key).css({height: '1px'});
}
}
});
I looking for a way thru which I can catch hold of the div, which is 20px away from either the left or right side of the mouse pointer, and drag it.
Any suggestions much appreciated.
You can use CSS styling to get this result. We set the ::after size to 100% - 20px on either the left or top, depending if it's the horizontal or vertical line. We then set our width or height, depending on if we're adjusting the row or column, to either 100% or the buffer size(40px, because we want 20px on either side of the line).
I realize that sounds a little confusing, so I'll split them up. Here's the vertical:
.vguide1,.vguide2,.vguide3 {
border-left: 1px solid blue;
padding-bottom: 20px;
position: absolute;
width:1px;
height:650px;
}
.vguide1::after,.vguide2::after,.vguide3::after {
content: '';
position: absolute;
left: calc(50% - 20px);
width: 40px;
height: 100%;
cursor: col-resize;
}
Horizontal:
.hguide1,.hguide2,.hguide3 {
padding-right: 20px;
position: absolute;
width:850px;
height:1px;
border-top: 1px solid blue;
}
.hguide1::after,.hguide2::after,.hguide3::after {
content: '';
position: absolute;
top: calc(50% - 20px);
width: 100%;
height: 40px;
cursor: row-resize;
}
With shading to show the hit box: https://jsfiddle.net/Ljxpj5bt/27/
Without hit box: https://jsfiddle.net/Ljxpj5bt/28/

get the velocity value of a swipe?

hammer.js (http://hammerjs.github.io/recognizer-swipe/) checks the velocity of the swipe, I wonder how to get this value in order to determent how big the margin-left of my element #visitContent should be and get a smoother swipe.
html
<section id="visits">
<div id='visitsContent'>
<div></div>
<div></div>
<div></div>
</div>
</section>
Javascript
var visits = document.getElementById('visits');
var mc = new Hammer(visits, {velocity:0.80});
mc.on("swipeleft", function(ev) {
$('#visitsContent').css({
marginLeft : '-=200px'
})
});
mc.on("swiperight", function(ev) {
$('#visitsContent').css({
marginLeft : '+=200px'
})
});
sass
#visits
width: 100%
padding: 0px
border-bottom: none
background-color: $backgroundColorSecond
margin-bottom: 10px
margin-left: -20px
#visitsContent
div
width: 180px
height: 180px
float: left
margin-left: 5px
background-color: green
color: black
text-align: center
there is also a fiddle
http://jsfiddle.net/mL911mqn/
Judging from your jsfiddle it looks like you're using the pan gesture now instead of the swipe gesture. So in your pan event handler, you should be able to access the drag velocity like this:
function panGestureHandler(ev){
var velocity = ev.gesture.velocity;
var velocityX = ev.gesture.velocityX;
var velocityY = ev.gesture.velocityY;
console.log("horizontal drag speed = " + velocityX);
}

keep the background image fixed position and centered

In my project, I need to show a small image in center of the visible part of the container, with respect to the window i.e .loader. Even when the user scrolls the page, the image should be visible in center of .loader.
I successfully implemented this but now I am facing a edgecase which is when user scrolls the page "up to the header" or "down to the footer", the small image is hiding. demo.
This is actually normal behaviour but in these edgecases, I want the image to stick to top/bottom end of the .loader container.
What I want:
Keep the small image always at center of .loader container. (I already implemented this)
when scrolled to any end of .loader container, the image should stick to that end instead of hiding behind the container.
Fiddle
A solution using just css is preferred. I am looking for browser support in IE9+, chrome and firefox.
.header {
height: 600px;
width: 650px;
background-color: grey;
}
.left-side {
height: 300px;
width: 150px;
float: left;
background-color: red;
}
.loader {
background-image: url('http://i.imgur.com/U2njI.jpg');
margin-left: 150px;
height: 1500px;
width: 500px;
background-position: 345px center;
background-repeat: no-repeat;
background-attachment: fixed;
background-color: cornflowerblue;
}
.footer {
height: 600px;
width: 650px;
background-color: silver;
}
<div class="header"></div>
<div class="left-side"></div>
<div class="loader"></div>
<div class="footer"></div>
Here is a working solution with javascript, I hope its behaviour is how you expect it to be. I'm unfortunately not able to test it on IE9 right now but it should work (DEMO):
document.addEventListener('DOMContentLoaded',function() {
var loader = document.querySelector('.loader'),
loaderRect = loader.getBoundingClientRect(),
loaderTop = loaderRect.top + document.body.scrollTop,
loaderBottom = loaderTop + loader.offsetHeight,
initialBgPos = loader.style.backgroundPosition,
imageHeight = 141;
function onScroll() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(loaderTop >= (scrollTop + (window.innerHeight - imageHeight)/2)) {
loader.style.backgroundPosition='345px ' + (loaderTop - scrollTop) + 'px';
} else if(loaderBottom <= (scrollTop + (window.innerHeight + imageHeight)/2)) {
loader.style.backgroundPosition='345px ' + (loaderBottom - scrollTop - imageHeight) + 'px';
} else {
loader.style.backgroundPosition = initialBgPos;
}
}
window.addEventListener('scroll', onScroll);
onScroll();
});
To achieve what I think you want. We have to set the position of the .loader div to fixed, then it'll always stay where it's placed, regardless of whether the user scrolls the page, the div will scroll too. In here's how to set the position of loader to fixed in CSS (you may also have to get the position of your fixed div):
.loader{
position: fixed;
left: 100px;
top: 300px;
}
Here's your upadted JSFiddle: http://jsfiddle.net/Ezhb4/4/

JQuery Mousemove div class e.pageX positions

I am using this code:
$('.my_img').mousemove(function(e){
$('.mycls').css("left",e.pageX-20+"px");
$('.mycls').css("top",e.pageY-10+"px");
});
then...
<div class="mycls">I Move</div>
then...
<img class="my_img" src="myimg.png" />
My problem is that if I add any div's above these divs the position changes and mycls is no longer at mouse position.
So if I was to add to extra div's after the body like this:
<div>ONE</div>
<div>TWO</div>
...then the rest of the code...I will lose the position :o/
Any ideas on how to sort this?
Since e.pageX and e.pageY values are relative to the entire page, your code shouldn't be affected by adding new elements. If you set top and left to an element, it defines its distance from the top and left of the page.
The only case where it could be problematic is if you have position:relative set on any parent elements of the mycls div. Remove that position:relative, so that top and left refer to the entire page and not the parent element.
simply add a CSS position:absolute; to your movable element .mycls
var img = document.getElementById("my_img");
var cls = document.getElementById("mycls");
img.onmousemove = function(e){
cls.style.left = e.clientX-20 + "px";
cls.style.top = e.clientY-10 + "px";
};
#mycls {
background-color: rgba(255,255,255,0.8);
position: fixed;
left: 0;
top: 0;
font-family: sans-serif;
padding: 10px;
border-radius: 5px;
border: 1px solid rgba(0,0,0,0.8);
}
#my_img {
width: 420px;
height: 200px;
background-color: #333; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_img">
<div id="mycls">
Your message here
</div>
</div>
Here's an example of how I have done this in the past ... importantly
the div that is moving is a child of the container so that a any mousemove events it triggers are bubbled to the parent for handling

How to keep a floating div centered on window resize (jQuery/CSS)

Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?
To help explain, I imagine the pseudocode would look something like:
div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)
UPDATE
My query having been answered below, I wanted to post the final outcome of my quest - a jQuery extension method allowing you to center any block element - hope it helps someone else too.
jQuery.fn.center = function() {
var container = $(window);
var top = -this.height() / 2;
var left = -this.width() / 2;
return this.css('position', 'absolute').css({ 'margin-left': left + 'px', 'margin-top': top + 'px', 'left': '50%', 'top': '50%' });
}
Usage:
$('#mydiv').center();
This is easy to do with CSS if you have a fixed-size div:
.keepcentered {
position: absolute;
left: 50%; /* Start with top left in the center */
top: 50%;
width: 200px; /* The fixed width... */
height: 100px; /* ...and height */
margin-left: -100px; /* Shift over half the width */
margin-top: -50px; /* Shift up half the height */
border: 1px solid black; /* Just for demo */
}
The problem, of course, is that fixed-size elements aren't ideal.
The simplest way would be with the following CSS code:
#floating-div {
width: 50%;
border: 1px solid gray;
margin: 0 auto;
}
The key line of CSS code above is the "margin: 0 auto;" which tells the browser to automatically set the left/right margins to keep the div centered on the page, even when you resize the browser window.
Try this little article about Horizontal and Vertical centering. It is a little old and has a few hacks but you should be able to work out some test code from it.

Categories