How to make resizable with handle dynamically? without ui - javascript

I'm trying to create a function for drag and drop resizing and I have a problem. The script doesn't react to mouse cursor direction changes instantly. If I hold the button down and move cursor right, then left, it will only keep on increasing object's size for a moment.
demo
Javascript:
var re_dragging = false, re_om_x, re_om_y, re_o_x, re_o_y, re_n_x, re_n_y;
function resize(resize_btn){
resize_btn.mousedown(function(e){
e.preventDefault();
e.stopPropagation();
re_dragging = true;
re_om_x = e.pageX;
re_om_y = e.pageY;// origin mouse postion
target_wp = $(e.target).closest('.draggable_wp').find('.draggable_el');
});
$(document).mousemove(function(e){
if(re_dragging){
target_wp.width((e.pageX - re_om_x) + target_wp.width());
}
});
$(document).mouseup(function(e){
re_dragging = false;
});
};
var resize_btn = $('.draggable_btn_resize');
resize(resize_btn);
HTML:
<div class="draggable_wp">
<div class="wp_img">
<img src=""class="draggable_el">
</div>
<div class="btn">
<div class="draggable_btn_resize"></div>
</div>
</div>

You need update re_om_x after reseting width using re_om_x = e.pageX;.
And I add a new variable width, because in target_wp.width((e.pageX - re_om_x) + target_wp.width());, the target_wp.width() will bring in deviation, it is always get a int.
I rewrite mousemove as below:
$(document).mousemove(function (e) {
if (re_dragging) {
target_wp.width((e.pageX - re_om_x) + width);
width = (e.pageX - re_om_x) + width
re_om_x = e.pageX;
}
});
Here is demo. http://jsfiddle.net/U9vre/1/

For simplicity, see the jQuery UI function .resizable(). Just remember that you would then need to add the jqueryui .css and .js scripts to your page. You would then just need to call
$("#some_div_to_resize").resizable();

Related

jquery - Event while the mouse is held down

I have an image that I have given the id #scroller to. What I would like to do is move the scroller horizontally according to the x-coordinate of the mouse but only when it's held down. I'm trying to move scroller against a hroizontal line called #bar. The amount the scroller can move depends on the width of the bar. Here is my code so far.
$(document).ready(function() {
var barWidth = $("#bar").width();
var mouseDown = false;
$(document).mousedown(function() {
mouseDown = true;
});
$(document).mouseup(function() {
mouseDown = false;
});
$(document).on("mousemove", function(e) {
if (mouseDown) {
if (e.pageX >= barWidth) {
$("#debug").html(JSON.stringify(e.pageX, undefined, 4));
$("#scroller").css("left", barWidth);
} else {
$("#debug").html(JSON.stringify(e.pageX, undefined, 4));
$("#scroller").css("left", e.pageX);
}
}
});
});
The #debug just prints something out on to the screen. It helps in debugging. It's not working as expected. I want the scroller to move when the mouse is held down and moving.
You problem is likely in the fact that you didn't change position attribute for your scroller. It should be either style="position:absolute" or style="position:relative"
otherwise .css("left", barWidth) won't have effect. See js fiddle here:
https://jsfiddle.net/0m0j35oc/
More over it is better to track buttons on event itself(see this question for more details) as mouseup/mousedown event might be triggered outside of the page effectively getting you cached state out of sync. See example here:
https://jsfiddle.net/g0uqLL9n/

Trying to make a drag to stretch element, why is it so jumpy?

I'm trying to create a dragbar so users can stretch the height or width of an element on my page (not interested in using HTML resize).
It seems like I'm pretty close, but I can't figure out why
1) the moveable bar is jumping all over the page
2) the adjustable div is flickering as the size changes (or sometimes disappearing completely).
You can see the demo at http://jsfiddle.net/dYUz7/
Here's the source
var elem = $('.layout');
var resizeBar = $('.resize-bar',elem),
adjustableWrapper = $('.layout-container-wrapper',elem),
posDir = 'Left',
pos = 'X';
if($(elem).hasClass('layout-updown')){
posDir = 'Top';
pos = 'Y';
}
var startPos = resizeBar[0]['offset'+posDir], i = resizeBar[0]['offset'+posDir];
resizeBar.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
console.log(event);
$(document).on('mousemove', mousemove);
$(document).on('mouseup', mouseup);
});
function mousemove(event) {
i = event['page'+pos] - startPos;
if(pos==='X') return changeSizeWidth(i,event.offsetX);
return changeSizeHeight(i,event.offsetY);
}
function changeSizeWidth(i,width){
resizeBar.css({left : i +'px'});
adjustableWrapper.css({'width': width +'px'});
console.log(adjustableWrapper.css('width'));
}
function changeSizeHeight(i,height){
resizeBar.css({top : i +'px'});
adjustableWrapper.css({'height': height +'px'});
console.log(adjustableWrapper.css('height'));
}
function mouseup() {
$(document).unbind('mousemove', mousemove);
$(document).unbind('mouseup', mouseup);
}
Please don't respond with suggestions for using libraries, I have jQuery in the sample, but I'm using angular in the project, and am trying to not add a bunch of other libraries at this point.
I ended up getting this working by changing the move from the move-bar element to the element which needs to grow or shrink.
The css is a bit messed up, but here's an updated jsfiddle of the result
http://jsfiddle.net/dYUz7/2/
function changeSizeWidth(left){
adjustableWrapper.css({'width': left +'px'});
}

without jquery i need to find out if the mouse is over an element, not determine when it becomes over (in case it doesn't move to trigger onmouseover)

without jquery
basically what I am looking for is the ability to see if the mouse is over a div when a countdown finishes
if the user is over the div then perform action for that div
onmouseover only triggers when the mouse crosses the threshold of the div, if the mouse hasn't moved it wouldn't trigger, so that wouldn't work
I need to determine if the mouse is currently over a div at a specific point in time, if it has moved or not from the starting point
all of my hunting has only found onmousover, and nothing to see if the mouse just happens to be there to begin with
I don't have the javascript skills to determine overall coords of div, then map mouse coords and see if it fits there... which is what I believe I need to do
After reading the second answer (the one with millions of a elements) on this SO question, I've came up with this method works without moving the mouse on page load, without involving millions of elements.
HTML
<div id=t></div>
CSS
#t {
/* for illustrative purposes */
width: 10em;
height: 5em;
background-color: #0af;
}
#t:hover {
border-top-style: hidden;
}
JavaScript
document.addEventListener('click', function () {
var c = window.getComputedStyle(document.getElementById('t')).getPropertyValue('border-top-style');
if (c === 'hidden') {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
As stated earlier, bind to the finish event of your countdown instead of the click event on the document.
You may also use any CSS style that's changed on :hover, I chose border-top-style as it is conspicuous. If you're using a border, choose something else.
Here's a jsFiddle.
set a flag to true onmouseover and to false onmouseleave. when countdown finishes if flag is true then it is over element.
HTML
<div id="div-name">the section of the code i am working with has a countdown timer, when it reaches 0 i need to know if the mouse is over a specific box</div>
<button id="notification" onclick="javascript: letsCountIt(5);">click to start countdown</button>
JS
window.ev = false;
document.getElementById('div-name').onmouseover = function () {
window.ev = true;
console.log(window.ev);
}
document.getElementById('div-name').onmouseout = function () {
window.ev = false;
console.log(window.ev);
}
window.letsCountIt = function (cdtimer) {
cdtimer--;
document.getElementById('notification').innerHTML = cdtimer;
if (cdtimer == 0) {
if (window.ev === true) {
alert('over');
} else {
alert('not over');
}
} else {
setTimeout(function(){letsCountIt(cdtimer);}, 1000);
}
}
Look into document.elementFromPoint . When you pass an x,y to elementFromPoint, it will return whatever element (or <body>, if no other specific element) is at that point. You can easily check if this element is the element you want.
The problem then is finding out what point your mouse is at. How to get the mouse position without events (without moving the mouse)? seems to say - don't. At least use mouseMove to track the cursor. The linked question gives examples of how to do so. (Look to the lower scoring answers, as the higher ones only got points for being snarky.)
Just want to say that, I think jQuery's mouseenter and mouseleave events would make this a lot easier, but if you can't use them, maybe this will help you.
Depending on how your page is laid out, this may not be too difficult. You can get the position of your element using the following. Quoting from another answer
element.offsetLeft and element.offsetTop are the pure javascript
properties for finding an element's position with respect to its
offsetParent; being the nearest parent element with a position of
relative or absolute
So, if your element is positioned relatively to the body, so far so good (We don't need to adjust anything).
Now, if we attach an event to the document mousemove event, we can get the current coordinates of the mouse:
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
}, false);
Now we just need to determine if the mouse falls within the element. To do that we need the height and width of the element. Quoting from another answer
You should use the .offsetWidth and .offsetHeight properties. Note
they belong to the element, not .style.
For example:
var element = document.getElementById('element');
var height = element.offsetHeight;
var width = element.offsetWidth;
Now we have all the information we need, and just need to determine if the mouse falls within the element. We might use something like this:
var onmove = function(e) {
var minX = element.offsetLeft;
var maxX = minX + element.offsetWidth;
var minY = element.offsetTop;
var maxY = minY + element.offsetHeight;
if(e.clientX >= minX && e.clientX <= maxX)
//good horizontally
if(e.clientY >= minY && e.clientY <= maxY)
//good vertically
}
This code works, but the mouse has to be moved once after page load.
var coords;
var getMouseCoordinates = function (e) {
'use strict';
return {
x: e.clientX,
y: e.clientY
};
};
document.addEventListener('mousemove', function (e) {
coords = getMouseCoordinates(e);
}, false);
document.addEventListener('click', function () {
var divCoords = document.getElementById('t').getBoundingClientRect();
if (coords.x >= divCoords.left && coords.x <= divCoords.right && coords.y >= divCoords.top && coords.y <= divCoords.bottom) {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
You wouldn't bind to the click event of document, but rather the finish event of your countdown.
Here's an example. Try clicking in the output window.
You don't need any coordinates or mouse events, if you know a selector for that element:
if (document.querySelector('#elementSelector:hover')) {
alert('I like it when you touch me!');
}

Determine whether mouse is always on the bottom of the page

How can I determine whether mouse is always on the bottom of the viewport? Let us assume that by bottom we mean the bottom 100 pixels of a given page (on a long scrolling page).
this is an example, check the arrow
http://discover.store.sony.com/tablet/#design/weight-distribution
Easy!
Calculate how much of that "bottom" area is showing in the current window with window.screen.height and document.height.
Then use onmousemove event to calculate if the mouse is stepping over that area.
Create a blank div with the dimensions that you want, use CSS to position:absolute; it on the bottom and z-index it above the other elements, then create a onHover to detect if the mouse is there
EDIT
This might work as a solution to avoid using CSS method above (untested)
$(function(){
$.mousemove(function(e){
var wHeight = $(window).height();
var yMouse = e.pageY;
if(yMouse > (wHeight - 100)) {
// Do something
}
});
});
I think i solved myself based on Pastor Bones code:
you have to calculate the window scrolltop
var scrollT = $(window).scrollTop() + wHeight;
so:
$(function(){
$.mousemove(function(e){
var wHeight = $(window).height();
var scrollT = $(window).scrollTop() + wHeight;
var yMouse = e.pageY;
if(yMouse > (scrollT - 100)) {
// Do something
}
});
});

JQuery/JQueryUI hortizontal divider

recently for a website I am working on I wanted to create a horizontal divider capable of resizing two elements on a page using jquery.
Basically:
Content
___Divider_____
Content
When: the divider is dragged, it should resize the "Content" elements either side of it to the users desired size.
Here is what i have so far.
<div id="WorkRequests"></div>
<div id="Divider" style="height:10px; padding:5px; cursor:n-resize;"><hr /></div>
<div id="WorkRequest_Ajax"></div>
And the script:
var totalHeight = $("#Divider").parent().height();
function ResizePage(divPosition) {
var validDrag = true;
// Math
var minPercent = totalHeight * 0.25;
var minBuffer = totalHeight * 0.05;
var topHeight = divPosition.top - $("#content").position().top;
var bottomHeight = (totalHeight - divPosition.top);
// Check Drag
if (topHeight < minPercent) {
validDrag = false;
$("#WorkRequests").height(minPercent + minBuffer);
}
if (bottomHeight < minPercent) {
validDrag = false;
$("#WorkRequest_Ajax").height(minPercent + minBuffer);
}
// Set Heights
if (validDrag) {
$("#WorkRequests").height(topHeight);
$("#WorkRequest_Ajax").height(bottomHeight);
}
return validDrag;
}
$("#Divider").draggable({ axis: "y", drag: function (event, ui) { return ResizePage($(this).position()); } });
However when I drag the divider it simply jumps around and locks at either extremity, I have tried many different calculations etc, but I am afraid I just simply do not understand the factors in resizing both elements.
So does anyone know a jquery plugin that will do this for me, or how i can fix my attempt?
Thanks,
Alex.
You may also checkout the UI.Layout jQuery plugin. Here's a demo.
You should just use the jquery resizable interaction : http://jqueryui.com/demos/resizable/
It's easy enough to restrict the dragging areas so you can only resize horizontally (but I think what you actually need is a vertically resizable area)

Categories

Resources