I'm trying to write jQuery plugin which replace default cursor to necessary image, but I have a problem with mouseleave. It doesn't fire because cursor always before child div and never leave it, so cursor never changes back to default.
DEMO
Any ideas how to fix it?
By the way: jQuery mouseleave behavior is little strange. It fires only when you leave your div and all childe divs.
DEMO 2
My code:
// Plugin changing cursor before element
;
(function ($) {
$.fn.changeCursor = function (cursorPicUrl, dx, dy) {
function inFunction(e) {
$cursor.show();
return false;
}
function outFunction(e) {
$cursor.hide();
return false;
}
function moveFunction(e) {
var x = e.clientX-100;
var y = e.clientY-100;
$cursor.css({
"transform": "translate(" + x + "px," + y + "px)"
});
}
var $cursor = $('<div id="#custom-cursor"></div>').css({
/*cursor: none;*/
width: '150px',
height: '150px',
background: 'url("' + cursorPicUrl + '") no-repeat left top',
position: 'absolute',
display: 'none',
'z-index': '10000'
});
this.append( $cursor )
.on( "mouseenter", inFunction )
.on( "mouseleave", outFunction )
//.hover( inFunction, outFunction)
.mousemove( moveFunction );
return this;
};
})(jQuery);
$(document).ready(function () {
var url = 'http://placehold.it/150x150';
$('#test-area').changeCursor( url );
});
UPDATE
My solition here:
jquery.change-cursor
I made a couple of adjustments:
Store this in a variable up front.
Attach the cursor div to the body.
Add the top/left properties to the cursor.
DEMO
Javascript:
(function ($) {
$.fn.changeCursor = function (cursorPicUrl, dx, dy) {
var elem = this;
function inFunction(e) {
$cursor.show();
return false;
}
function outFunction(e) {
$cursor.hide();
return false;
}
function moveFunction(e) {
var x = e.clientX;
var y = e.clientY;
$cursor.css({
"transform": "translate(" + x + "px," + y + "px)"
});
}
var $cursor = $('<div id="#custom-cursor"></div>').css({
/*cursor: none;*/
width: '150px',
height: '150px',
background: 'url("' + cursorPicUrl + '") no-repeat left top',
position: 'absolute',
top: '0',
left: '0',
display: 'none'
});
$('body').append( $cursor );
elem.on( "mouseenter", inFunction )
.on( "mouseleave", outFunction )
.mousemove( moveFunction );
return this;
};
})(jQuery);
For anyone still looking something similar, try this (maybe):
$('#selector').css('cursor', 'url("/path/your_image.png"), auto');
PS: Doesn't work on primitive browsers!
Related
I am using Angular Material Bottom Sheet, but I want it in such a way, that it should get adjusted, when the user drags it up and down from the bottom.
I have used one plugin to resize the bottom sheet, but the bottom sheet is getting dragged up and down without resizing, it's bottom is not fixed.
Here's the working code in plunkar.
resizer.js:
angular.module('mc.resizer', []).directive('resizer', function($document) {
return function($scope, $element, $attrs) {
$element.on('mousedown', function(event) {
event.preventDefault();
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
if ($attrs.resizer == 'vertical') {
// Handle vertical resizer
var x = event.pageX;
if ($attrs.resizerMax && x > $attrs.resizerMax) {
x = parseInt($attrs.resizerMax);
}
$element.css({
left: x + 'px'
});
$($attrs.resizerLeft).css({
width: x + 'px'
});
$($attrs.resizerRight).css({
left: (x + parseInt($attrs.resizerWidth)) + 'px'
});
} else {
// Handle horizontal resizer
var y = window.innerHeight - event.pageY;
if((window.innerHeight-100 > y)&&(y>100)){
$element.css({
bottom: y + 'px'
});
$($attrs.resizerTop).css({
bottom: (y + parseInt($attrs.resizerHeight)) + 'px'
});
$($attrs.resizerBottom).css({
height: y + 'px'
});
}
}
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
};
});
I've tried using jquery's built in draggable and I've tried using custom drag functions with no avail. Both have their respected issues and I will try to highlight both of them.
Basically, I am trying to allow the dragging of an element that is on a scaled div container. The following methods work okay on a scaled element that is less than around 2. But if you go any higher than that, we see some issues.
Any help would be appreciated. Thank you for your time.
HTML
<div id="container">
<div id="dragme">Hi</div>
</div>
Method 1 (Jquery draggable function)
I've tried the jquery draggable function as you can see in this jsfiddle example.
The problems I found in this example are the following:
Biggest concern: The droppable container does not change when it is scaled up. So if the element is being dragged over part of the scaled container that isn't a part of it's original size, it will fail.
When you click to drag a div, it teleports a little bit away from the mouse and is not a seamless drag.
JS
var percent = 2.5;
$("#dragme").draggable({
zIndex: 3000,
appendTo: 'body',
helper: function (e, ui) {
var draggable_element = $(this),
width = draggable_element.css('width'),
height = draggable_element.css('height'),
text = draggable_element.text(),
fontsize = draggable_element.css('font-size'),
textalign = draggable_element.css('font-size');
return $('<div id="' + draggable_element.id + '" name="' + draggable_element.attr('name') + '" class="text">' + text + '</div>').css({
'position': 'absolute',
'text-align': textalign,
'background-color': "red",
'font-size': fontsize,
'line-height': height,
'width': width,
'height': height,
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
});
},
start: function (e, ui) {
$(this).hide();
},
stop: function (e, ui) {
$(this).show();
}
});
$("#container").droppable({
drop: function (event, ui) {
var formBg = $(this),
x = ui.offset.left,
y = ui.offset.top,
drag_type = ui.draggable.attr('id');
var element_top = (y - formBg.offset().top - $(ui.draggable).height() * (percent - 1) / 2) / percent,
element_left = (x - formBg.offset().left - $(ui.draggable).width() * (percent - 1) / 2) / percent;
$(ui.draggable).css({
'top': element_top,
'left': element_left
});
}
});
Method 2 - Custom drag function
I've tried using a custom drag function but it unusable after around a 2 scale.
jsfiddle on a scale(2) - Looks like the draggable div is having a seizure.
jsfiddle on a scale(2.5) - The draggable div flys away when you try to drag it.
JS
(function ($) {
$.fn.drags = function (opt) {
opt = $.extend({
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $parent = this;
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
$(this).addClass('active-handle')
var $drag = $parent.addClass('draggable');
}
var
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
follow = function (e) {
$drag.offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
})
};
$(window).on("mousemove", follow).on("mouseup", function () {
$drag.removeClass('draggable');
$(window).off("mousemove", follow);
});
e.preventDefault(); // disable selection
}).on("mouseup", function () {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle');
$parent.removeClass('draggable');
}
});
}
})(jQuery);
$("#dragme").drags({}, function (e) {});
Here are a few of my findings to make sure dragging on a scaled container works for method one. The only caveat is to make sure you have var percent as the scaled percentage declared before any of these actions happen.
First, use this code at the top of your javascript. This wil help making sure that the droppable area works with a sacled container.
$.ui.ddmanager.prepareOffsets = function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth * percent, height: m[ i ].element[ 0 ].offsetHeight * percent }); } };
Here are a few functions that are necessary to fix the drag so it works on a scaled container.
function dragFix(event, ui) { var changeLeft = ui.position.left - ui.originalPosition.left, newLeft = ui.originalPosition.left + changeLeft / percent, changeTop = ui.position.top - ui.originalPosition.top, newTop = ui.originalPosition.top + changeTop / percent; ui.position.left = newLeft; ui.position.top = newTop; }
function startFix(event, ui) { ui.position.left = 0; ui.position.top = 0; var element = $(this); }
You will want this if you want to enable the element to be resizable on a scaled container.
function resizeFix(event, ui) { var changeWidth = ui.size.width - ui.originalSize.width, newWidth = ui.originalSize.width + changeWidth / percent, changeHeight = ui.size.height - ui.originalSize.height, newHeight = ui.originalSize.height + changeHeight / percent; ui.size.width = newWidth; ui.size.height = newHeight; }
To make an element draggable, I use the following function.
$("ELEMENT").resizable({ minWidth: - ($(this).width()) * 10, minHeight: - ($(this).height()) * 10, resize: resizeFix, start: startFix });
$("ELEMENT").draggable({ cursor: "move", start: startFix, drag: dragFix }); }
A similar problem is mentioned here: jquery - css "transform:scale" affects '.offset()' of jquery
It seems the problem arises from the fact that jQuery fails to return exact size for scaled elements and therefore failing setting right offset values to the element.
To solve this, he is suggesting first setting scale to 1 and setting offset and then again resetting scale value.
But this alone does not solve the problem here. Since mouse position is taken while it is scaled, position values should also be divided by scale value.
Here is an edited version of code:
var scl = 2.5;
var
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top/scl + drg_h - e.pageY/scl,
pos_x = $drag.offset().left/scl + drg_w - e.pageX/scl;
follow = function(e) {
var size = {
top:e.pageY/scl + pos_y - drg_h+scl*2,
left:e.pageX/scl + pos_x - drg_w+scl*2
};
$drag.parent().css("transform","scale(1)");
$drag.offset(size);
$drag.parent().css("transform","scale("+scl+")");
};
Note: I only replaced scale value for transform tag, since I am using chrome. You can also replace all instances or instead you can use a different class with 1 scale value.
JSFiddle is also here.
Here is an example of simple drag with scaling, however, in prue dom.
<style>
#dragme {
position:absolute;
border:1px solid red;
background:pink;
left:10px;
top:20px;
width:100px;
height:200px;
}
#container {
transform: scale(2,2) translate(100px,100px);
position:relative;
border:1px solid green;
background:grey;
width:200px;
height:300px;
}
</style>
<body>
<div id="container">
<div id="dragme">Hi</div>
</div>
<script>
var dragme=document.getElementById("dragme");
var container=document.getElementById("container");
dragme.onmousedown=function Drag(e){
this.ini_X = this.offsetLeft-e.clientX/2;
this.ini_Y = this.offsetTop-e.clientY/2;
container.onmousemove = move;
container.onmouseup = release;
return false;
}
function move(e){
e.target.style.left = e.clientX/2 + e.target.ini_X + 'px';
e.target.style.top = e.clientY/2 + e.target.ini_Y + 'px';
}
function release(){
container.onmousemove=container.onmouseup=null;
}
</script>
</body>
Found a lightway draggable function. How can I lock the draggable black block in parent area? Do i need to do a width and height to limit black block area?
online sample http://jsfiddle.net/zqYZG/
.drag {
width: 100px;
height: 100px;
background-color: #000;
}
.box{
width: 500px;
height: 400px;
background-color:red;
}
jQuery
(function($) {
$.fn.draggable = function(options) {
var $handle = this,
$draggable = this;
options = $.extend({}, {
handle: null,
cursor: 'move'
}, options);
if( options.handle ) {
$handle = $(options.handle);
}
$handle
.css('cursor', options.cursor)
.on("mousedown", function(e) {
var x = $draggable.offset().left - e.pageX,
y = $draggable.offset().top - e.pageY,a
z = $draggable.css('z-index');
$draggable.css('z-index', 100000);
$(document.documentElement)
.on('mousemove.draggable', function(e) {
$draggable.offset({
left: x + e.pageX,
top: y + e.pageY
});
})
.one('mouseup', function() {
$(this).off('mousemove.draggable');
$draggable.css('z-index', z);
});
// disable selection
e.preventDefault();
});
};
})(jQuery);
$('.drag').draggable();
Here is a simple way to do it, using the getBoundingClientRect() function: updated JSFiddle
This just constrains the l and t variables from your original code, to be within the parent node's dimensions.
See containment option!
use :
$( ".selector" ).draggable({ containment: "parent" });
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to scroll the page vertically without using the scrollbar.
instead i want to use 2 image tags for scrolling the page.
this was the code i tried for the scroll but it didnt look good:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/css">
div.mousescroll {
overflow: hidden;
}
div.mousescroll:hover {
overflow-y: scroll;
}
</style>
<script language="javascript" type="text/javascript">
$(function() {
$(".wrapper1").scroll(function left() {
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function right() {
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
</script>
<div id="first" class="wrapper1 ">
<div id="first2" class=" div1 ">
</div>
<br />
</div>
<br />
<div id="second" class="wrapper2 mousescroll">
<div id="second2" style=" overflow-x:scroll" class="div2">
<table>
...............
</table>
</div>
</div>
imagine that the width of this table is 2000px and instead of scrollbar i wanna use two image tags that can do the scroll job.
can anyone help me with this?
$(window).load(function () {
(function ($) {
jQuery.fn.extend({
slimScroll: function (o) {
var ops = o;
//do it for every element that matches selector
this.each(function () {
var isOverPanel,
isOverBar,
isDragg,
queueHide,
barHeight,
divS = "<div></div>",
minBarHeight = 30,
wheelStep = 30,
o = ops || {},
cwidth = o.width || "auto",
cheight = o.height || "250px",
size = o.size || "7px",
color = o.color || "#000",
position = o.position || "right",
opacity = o.opacity || 0.4,
alwaysVisible = o.alwaysVisible === true;
//used in event handlers and for better minification
var me = $(this);
//wrap content
var wrapper = $(divS)
.css({
position: "relative",
overflow: "hidden",
width: cwidth,
height: cheight,
})
.attr({ class: "slimScrollDiv" });
//update style for the div
me.css({
overflow: "hidden",
width: cwidth,
height: cheight,
});
//create scrollbar rail
var rail = $(divS).css({
width: "15px",
height: "100%",
position: "absolute",
top: 0,
});
//create scrollbar
var bar = $(divS)
.attr({
class: "slimScrollBar ",
style: "border-radius: " + size,
})
.css({
background: color,
width: size,
position: "absolute",
top: 0,
opacity: opacity,
display: alwaysVisible ? "block" : "none",
BorderRadius: size,
MozBorderRadius: size,
WebkitBorderRadius: size,
zIndex: 99,
});
//set position
var posCss = position == "right" ? { right: "1px" } : { left: "1px" };
rail.css(posCss);
bar.css(posCss);
//wrap it
me.wrap(wrapper);
//append to parent div
me.parent().append(bar);
me.parent().append(rail);
//make it draggable
bar.draggable({
axis: "y",
containment: "parent",
start: function () {
isDragg = true;
},
stop: function () {
isDragg = false;
hideBar();
},
drag: function (e) {
//scroll content
scrollContent(0, $(this).position().top, false);
},
});
//on rail over
rail.hover(
function () {
showBar();
},
function () {
hideBar();
}
);
//on bar over
bar.hover(
function () {
isOverBar = true;
},
function () {
isOverBar = false;
}
);
//show on parent mouseover
me.hover(
function () {
isOverPanel = true;
showBar();
hideBar();
},
function () {
isOverPanel = false;
hideBar();
}
);
var _onWheel = function (e) {
//use mouse wheel only when mouse is over
if (!isOverPanel) {
return;
}
var e = e || window.event;
var delta = 0;
if (e.wheelDelta) {
delta = -e.wheelDelta / 120;
}
if (e.detail) {
delta = e.detail / 3;
}
//scroll content
scrollContent(0, delta, true);
//stop window scroll
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
};
var scrollContent = function (x, y, isWheel) {
var delta = y;
if (isWheel) {
//move bar with mouse wheel
delta = bar.position().top + y * wheelStep;
//move bar, make sure it doesn't go out
delta = Math.max(delta, 0);
var maxTop = me.outerHeight() - bar.outerHeight();
delta = Math.min(delta, maxTop);
//scroll the scrollbar
bar.css({ top: delta + "px" });
}
//calculate actual scroll amount
percentScroll =
parseInt(bar.position().top) /
(me.outerHeight() - bar.outerHeight());
delta = percentScroll * (me[0].scrollHeight - me.outerHeight());
//scroll content
me.scrollTop(delta);
//ensure bar is visible
showBar();
};
var attachWheel = function () {
if (window.addEventListener) {
this.addEventListener("DOMMouseScroll", _onWheel, false);
this.addEventListener("mousewheel", _onWheel, false);
} else {
document.attachEvent("onmousewheel", _onWheel);
}
};
//attach scroll events
attachWheel();
var getBarHeight = function () {
//calculate scrollbar height and make sure it is not too small
barHeight = Math.max(
(me.outerHeight() / me[0].scrollHeight) * me.outerHeight(),
minBarHeight
);
bar.css({ height: barHeight + "px" });
};
//set up initial height
getBarHeight();
var showBar = function () {
//recalculate bar height
getBarHeight();
clearTimeout(queueHide);
//show only when required
if (barHeight >= me.outerHeight()) {
return;
}
bar.fadeIn("fast");
};
var hideBar = function () {
//only hide when options allow it
if (!alwaysVisible) {
queueHide = setTimeout(function () {
if (!isOverBar && !isDragg) {
bar.fadeOut("slow");
}
}, 1000);
}
};
});
//maintain chainability
return this;
},
});
jQuery.fn.extend({
slimscroll: jQuery.fn.slimScroll,
});
})(jQuery);
//invalid name call
$("#Id").slimscroll({
color: "#aaa",
size: "6px",
width: "392px",
height: "525px",
});
});
So I have an object or div that is a square 10x10 pixels. I want to be able to click somewhere in the browser window that causes the div to gradually move towards the point I clicked.
jQuery
$(document).click(function(event) {
var x = event.pageX,
y = event.pageY;
$('div').animate({
top: y,
left: x
}, 1000);
});
CSS
div {
background: red;
padding: 5px;
position: absolute;
}
HTML
<div>hello</div>
jsFiddle.
$(document).click(function(event) {
$('#divID').css({
'position': 'absolute',
'left': event.clientX + document.body.scrollLeft,
'top': event.clientY + document.body.scrollTop });
});
Demo
jQuery code
$("body").bind("click", function(e){
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("span").text("Clicked at " + str);
});
after getting this you need to update your div.style.left and div.style.top !