I am writing a plugin that creates a select marquee box when the mouse is clicked on a canvas div. So far i've written the plugin with the click() and mousemove() events adjacent to each other in the code (i dont know of any way to embed events inside other events). But this becomes a problem when the mouse moves over the canvas before a click. Does anyone know how to initialize a mousemove handler with a click?
Here is the code i have written so far:
$.fn.createBox = function(id) {
$(id).css({
cursor:'crosshair'
});
$(id).click(function(e) {
var clickLocX = e.pageX;
var clickLocY = e.pageY;
$('<div>').attr({
'class':'newBox',
'ctr':'on'
})
.css({
top:clickLocY,
left:clickLocX
})
.appendTo(id);
});
//Mousemove must be initialized only AFTER the click. HOW TO DO THIS?
$(id).mousemove(function(e){
var XpageCoord = e.pageX;
var YpageCoord = e.pageY;
window.Xloc = XpageCoord;
window.Yloc = YpageCoord;
var boxOffset = $('.newBox').offset();
var boxHeight = YpageCoord - boxOffset.top;
var boxWidth = XpageCoord - boxOffset.left;
$('.newBox').css({
height:boxHeight + 'px',
width:boxWidth + 'px'
});
});
}
Just set the mousemove handler from within the click handler and use a flag to determine whether or not it has already been set to avoid adding it multiple times.
EDIT: An example
assignedMoveHandler = false;
$(id).click(function(e) {
// other stuff...
if(!assignedMoveHandler) {
$(id).mousemove(function(e) {
// mouse move handling code...
});
assignedMoveHandler = true;
}
}
I use a global here which you may or may not care about, I lookup the jquery object twice, etc., so it could be cleaned up a bit, but this is the general idea. When the click handler fires you check to see if you've assigned a mousemove handler yet. If not, assign it.
Related
i am using angular1's component design to build this application. i have made a directive with does the ripple effect on a button when user clicks on it. this is a common behaviour so i have taken it in the directive.
now i want to add another event listener to the same button from the component controllers $postLink() hook which causes directive event listener to fail in execution.
how to solve this issue. i want both events listened.
below is my ripple effect directive. i am using commonjs to load the modules so don't be bothered by that.
var app=require('../../../../Development/Assets/Js/appConfig');
app.directive('wave',waveConig);
waveConig.$inject=['$compile','$timeout'];
function waveConig($compile,$timeout){
return{
restrict:'A',
link:waveLink
};
function waveLink(scope,elem,attr){
var waveColor = attr.color;
elem.unbind('mousedown').bind('mousedown', function (ev) {
var el = elem[0].getBoundingClientRect();
var top = el.top;
var left = el.left;
var mX = ev.clientX - left;
var mY = ev.clientY - top;
var height = elem[0].clientHeight;
var rippler = angular.element('<div/>').addClass('wave');
rippler.css({
top: mY + 'px',
left: mX + 'px',
height: (height / 2) + 'px',
width: (height / 2) + 'px',
});
if (waveColor !== undefined || waveColor !== "") {
rippler.css('background-color', waveColor);
}
angular.element(elem).append(rippler);
$compile(elem.contents())(scope);
$timeout(function () {
angular.element(rippler).remove();
}, 500);
});
}
}
below is my component controller code.
verifyCtr.$inject=['$element','verifyService','$scope'];
function verifyCtr($element,verifyService,$scope){
console.log('verify component is up and working');
var $this=this;
var serviceObj={
baseUrlType:'recommender',
url:'https://httpbin.org/ip',
method:1,
data:{}
};
$this.$onInit=function(){
verifyService.getData(serviceObj,{
success:function(status,message,data){
$this.data=data;
},
error:function(status,message){
alert(status,'\n',message);
}
});
};
$this.$onChanges=function(changes){};
$this.$postLink=function(){
angular.element(document.querySelector('.addNewTag')).bind('click',function(){
console.log('hi there you clicked this btn');
});
};
$this.$onDestroy=function(){
angular.element(document.querySelector('.addNewTag')).unbind('click');
var removeListener=$scope.$on('someEvent',function(ev){});
removeListener();
};
}module.exports=verifyCtr;
when i run it. the component click event-listener is fired. but the directive fails to execute. i don't know whats causing this issue and i want both of them to work.
it took a while to figure it out.
document.querySelector('.class-name') ;
returns a array of html elements. and
angular.element(elem).bind()
works on one single angular element. so i had to use a unique way of identifying the element i,e by the Id. so what i did was
angular.element(document.querySelector('#id')).bind();
there is other ways of doing it by the classname also . we can itreate over the array and get our element and bind the event to it.
i would like some help with a javascript project.What i'm trying to do ,is have two functions that initiate when mouse is moved,but only one of them works every time
For example,if i do this
var mouseX;
var mouseY;
document.onmousemove = captureMouse;
document.onmousemove = function(){console.log("check");}
function captureMouse(ev){
ev = ev || window.event;
var mousePos= mouseCoords(ev);
mouseX=mousePos.x;
mouseY=mousePos.y;
document.getElementById("coordinput").value=mouseX;
return mousePos;}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX,y:ev.pageY};
}
return{
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
If i remove the second document.onmousemove,the first works fine and changes the values of the input field
If i leave it there,it constantly writes check like it should (it's for debug purposes),but the first one doesn't work
Any ideas on how to make multiple mouse events work?
use document.addEventListener('mousemove', yourCb); it allows multiple handlers
So I am writing a sort of drawing script, and it works fine right now (although the code still needs to be cleaned up and there needs to be more features), but when painting too much, mousemove lags incredibly. Here is the main Javascript:
$('#canvas').on('mousedown', function(){
going = !going;
$(this).on('mousemove', function(e){
if(cursor == 'paint' && going == true){
$('.fall').each(function(){
if ($(this).css("opacity") == 0){
$(this).remove();
};
});
var ps = $('#canvas').offset().top;
var t = (e.pageY - ps - $('.fall').height()).toString() + 'px';
var l = (e.pageX - $('.fall').width()).toString() + 'px';
$('.fall').css("margin_left",l);
$('.fall').css("margin_top",t);
var doit = '<div class="fall" style="position:absolute;margin-left:' + l + ';margin-top:' + t + ';background-color:'+ color +';box-shadow: 0px 0px 5px ' + color + ';"></div>'
$('#canvas').prepend(doit);
}
else if(cursor == 'erase'){
$('.fall').mouseenter(function(){
$(this).fadeOut('fast',function(){
$(this).remove()
});
});
};
});
Essentially, when you click in the section for drawing, if the paint button is clicked, you can draw: jsfiddle.
My issue:
If you draw too much, especially with starting and stopping, it does not append enough on the mousemove do to (I assume) the DOM being overwhelmed.
Question:
What would be an efficient way to add many many divs to the DOM without creating a lag? Is this possible?
Note:
this is a personal project and I am not interested in using previously created drawing APIs
There's a lot you can do to improve performance.
The code below is a heavy refactoring of the code in the question. At first glance it might appear to be less efficient as it has about double the number of lines of the original. However, line count isn't the issue here. Two basic principles apply:
do as little DOM interaction as possible in the mousemove handler, and as much as possible on mousedown.
include a "divider circuit" to limit the number of times the mousemove handler is called. This is achieved by detaching the mousemove event handler on every call and reattaching after a short delay, conditional on the mouse still being down.
Also see comments in the code.
jQuery(function($) {
...
var $canvas = $("#canvas");
var data = {
name: 'fall'//a unique string for namespacing the muousemove event.
};
$canvas.on('mousedown', function() {
going = !going;
data.$fall = $('.fall');//this collection is created once per mousedown then managed inside mm to avoid unnecessary DOM interaction
data.mousedown = true;
data.colorCSS = {
'background-color': color,
'box-shadow': '0px 0px 5px ' + color
};
data.fallWidth = data.$fall.width();
data.fallHeight = data.$fall.height();
attachMouseMoveHandler();
}).on('mouseup', function() {
data.mousedown = false;
}).trigger('mouseup');
function attachMouseMoveHandler() {
if(data.mousedown);
$canvas.on('mousemove.' + data.name, mm);//the event is namespaced so its handler can be removed without affecting other canvas functionality
}
//The mousemove handler
function mm(e) {
if(going && cursor == 'paint') {
data.$fall.each(function() {
data.$fall = data.$fall.not(this);//manage data.$fall rather than re-form at every call of mm()
var $this = $(this);
if ($this.css("opacity") == 0) {
$this.remove();
};
});
data.$fall = data.$fall.add($('<div class="fall" />').css(data.colorCSS).prependTo($canvas)).css({
'margin-left': (e.pageX - data.fallWidth) + 'px',
'margin-top': (e.pageY - $canvas.offset().top - data.fallHeight) + 'px'
});
}
else if(cursor == 'erase') {
data.$fall.mouseenter(function() {
data.$fall = data.$fall.not(this);//manage data.$fall rather than re-form at every call of mm()
var $this = $(this).fadeOut('fast', function() {
$this.remove();
});
});
};
$canvas.off('mousemove.' + data.name);
setTimeout(attachMouseMoveHandler, 50);//adjust delay up/down to optimise performance
}
});
Tested only for syntax
I had to make a number of assumptions, chiefly concerning what becomes fixed data on mousedown. These assumptions may be incorrect, so you will most probably still have some work to do, but as long as you work inside the overall framework above, there's a good chance that your performance issues will disappear.
I found this script by theZillion (http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery/) that makes a div draggable. I'm trying to use this script to move a div by class name. And not by ID.
I have an event handler that works, but not when I'm adding the script... The console shows no errors either. Any ideas about how to make this work?
This is the code I have:
function wrappmover(){
var moveEvent = "dice-window-wrapper";
var addClassArr= document.getElementsByClassName(moveEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", movewrapp, true);
}
function movewrapp() {
var classToMove = "dice-window-wrapper";
var elems = document.getElementsByClassName(classToMove);
var tzdragg = function(){
return {
startMoving : function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
a = document.getElementsByClassName(classToMove),
divTop = a.style.top,
divLeft = a.style.left;
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
tzdragg.move('elem',aX,aY);
}
},
stopMoving : function(){
document.onmousemove = function(){}
},
move : function(divid,xpos,ypos){
var a = document.getElementById(divid);
document.getElementById(divid).style.left = xpos + 'px';
document.getElementById(divid).style.top = ypos + 'px';
}
}
}();
Okay, so you want to have draggable elements on your page?
Take a look at the following code (and here's a working example). I hope you will find it self-explanatory, but just in case there are also comments:
// Wrap the module in a self-executing anonymous function
// to avoid leaking variables into global scope:
(function (document) {
// Enable ECMAScript 5 strict mode within this function:
'use strict';
// Obtain a node list of all elements that have class="draggable":
var draggable = document.getElementsByClassName('draggable'),
draggableCount = draggable.length, // cache the length
i; // iterator placeholder
// This function initializes the drag of an element where an
// event ("mousedown") has occurred:
function startDrag(evt) {
// The element's position is based on its top left corner,
// but the mouse coordinates are inside of it, so we need
// to calculate the positioning difference:
var diffX = evt.clientX - this.offsetLeft,
diffY = evt.clientY - this.offsetTop,
that = this; // "this" refers to the current element,
// let's keep it in cache for later use.
// moveAlong places the current element (referenced by "that")
// according to the current cursor position:
function moveAlong(evt) {
that.style.left = (evt.clientX - diffX) + 'px';
that.style.top = (evt.clientY - diffY) + 'px';
}
// stopDrag removes event listeners from the element,
// thus stopping the drag:
function stopDrag() {
document.removeEventListener('mousemove', moveAlong);
document.removeEventListener('mouseup', stopDrag);
}
document.addEventListener('mouseup', stopDrag);
document.addEventListener('mousemove', moveAlong);
}
// Now that all the variables and functions are created,
// we can go on and make the elements draggable by assigning
// a "startDrag" function to a "mousedown" event that occurs
// on those elements:
for (i = 0; i < draggableCount; i += 1) {
draggable[i].addEventListener('mousedown', startDrag);
}
}(document));
Load or wrap it in <script></script> tags as close as possible to </body> so that it doesn't block the browser from fetching other resources.
Actually, if you remove the comments, it's a very small function. Much smaller and more efficient than the one from the website you've provided.
A possible improvement
Consider replacing the anonymous wrapper with something like makeDraggable(selector); where selector is a CSS selector, so you could do crazy stuff like:
makeDraggable('#dragMe, #dragMeToo, .draggable, li:nth-child(2n+1)');
It can be achieved by using document.querySelectorAll that is able to perform complex CSS queries instead of a simple class name lookup by document.getElementsByClassName.
Things to watch out for
If the page has any scrolling - the drag will look broken; consider adjusting the positioning of the dragged element by scrollX and scrollY
This will obviously not work in Internet Explorer (figure it out yourself).
There might be memory leaks (needs profiling and testing).
EDIT: A solution for adding new draggable elements
So you want to be able to add more draggable elements? There are several approaches to tackle this. For example you could write a makeDraggable(element); function and call it on the element you're adding to the DOM. It will work of course, but let's have a look at something different, shall we?
Instead of querying the DOM in search of draggable elements and assigning them event listeners, why don't we assign just one for the "mousedown" event on document body.
When triggered, the event object will contain a reference to the target element which is the object the event has been dispatched on (the element you mousedown-ed). The relevant part of the code will now resemble this:
// Performs a check if the current element is draggable and if yes,
// then the dragging is initiated:
function startDragIfDraggable(evt) {
// Check if the target element (referenced by evt.target) contains a
// class named "draggable" (http://stackoverflow.com/questions/5898656/):
if (evt.target.classList.contains('draggable')) {
// Invoke startDrag by passing it the target element as "this":
startDrag.call(evt.target, evt);
}
}
// Listen for any "mousedown" event on the document.body and attempt dragging
// the target element (the one where "mousedown" occurred) if it's draggable:
document.body.addEventListener('mousedown', startDragIfDraggable);
And here's a working example of the above code. As a bonus it features a simulation of adding new draggable elements to the DOM.
In addition to being able to drag dynamically-added draggable elements, this approach will also save us some memory because we can now avoid assigning a bunch event listeners to a bunch of elements. However, if the application you're developing is very click-intensive (e.g. a game) then you might waste a little bit of CPU because of checks on every click.
I'm trying to drag and drop items on a page, but insteads of moving the item itself, I create a copy of it.
Here is my code. "copyDragDrop" is a div at the bottom of the page. It remains empty until the user strats dragging something.
function coordSouris()
{
return {
x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
y:event.clientY + document.body.scrollTop - document.body.clientTop
};
}
function drag()
{
var pos = coordSouris(event);
copie = event.srcElement.cloneNode(true);
document.getElementById('copieDragDrop').appendChild(copie);
copie.style.position = 'absolute';
copie.style.display = 'block';
document.onmousemove = mouseMove;
document.onmouseup = drop;
}
function mouseMove()
{
if (copie != null)
{
var pos = coordSouris(event);
copie.style.left = pos.x;
copie.style.top = pos.y;
}
}
function drop()
{
var divCopie = document.getElementById('copieDragDrop');
if (divCopie.hasChildNodes() )
{
while ( divCopie.childNodes.length >= 1 )
{
divCopie.removeChild(divCopie.firstChild);
}
}
}
This code creates the copy, starts to move it, but after a few pixels, the copy stops following the mouse. If I release the mouse, "onmouseup" is not fired, but the copy starts to follow the mouse again ! I've tried the code on several items, the same bug occurs
I don't understand anything, any help is more than welcome.
UPDATE : I juste realised that all elements I tried the code on had something in common : they contained or were included in an ASP.net hyperlink control. The same code works well on regular HTML elements. There must be some auto-generated javascript for links that interferes with my code.
Couldn't find the auto-generated code responsible for the issue, so I simply solvec this by replacing Hyperlink controls by standard HTML anchors.