Make img not to move in html - javascript

I have an image on my page, and I would like to listen to onmousemove events when the mouse is down. But I can't because in my browser (Firefox), when I drag an image, well actually I drag the image, which I don't want.
Here's my code:
JavaScript part:
document.onmousemove=getMouseCoordinates;
var x;
var y;
var clicked = false;
function getMouseCoordinates(event){
ev = event || window.event;
x = ev.pageX;
y = ev.pageY;
}
function onClickMap(){
var obj = document.getElementById("selectArea");
var tempX = x;
var tempY = y;
obj.style.left = tempX + "px";
obj.style.top = tempY + "px";
clicked = true;
}
function onMoveMap(){
if(clicked){
var obj = document.getElementById("selectArea");
var xToSize = Math.abs(parseInt(obj.style.left) - x);
var yToSize = Math.abs(parseInt(obj.style.top) - y);
obj.style.width = xToSize + "px";
obj.style.height = yToSize + "px";
}
}
HTML part:
<img src="pixels.png" id ="pixelDiv" usemap="#pixelMap" onClick="onClickMap()" onmousemove="onMoveMap()">

Here is a jQuery solution.
This will disable all drags:
$(document).bind("dragstart", function() {
return false;
});
If you want to disable drags only on img elements:
$(document).bind("dragstart", function(e) {
if (e.target.nodeName.toUpperCase() == "IMG") {
return false;
}
});

You can add a mousedown handler that just returns false. This seems to stop the dragging in FF.

ok it's nice, but I suppose it is something firefox specific, now I disabled the onlcick and onmove methods of my image, but I can stil drag the image
now I've found the solution, I was looking for this
http://www.develobert.info/2008/10/disable-firefox-image-drag.html

Related

Adding and Removing Event Listeners that Point to Function Declarations inside Constructor Function Expression

I have a problem figuring out how to organize these sets of expressions in a way that works. My constructor is a component of a game editor. Inside of this constructor I have a method that handles when the player clicks on an SVG on the document calling the moveObject expression. The move object correctly moves the object and it seems like inner onMouseMove function declaration is working as intended, but I cannot figure out how to remove these listeners.
I tried bind(this) on the removes too, but those didn't work. Before I try to mess with the function expressions and declarations I wanted to see if any of you had any thoughts on how I could write this code more efficiently. I feel like it is a little clunky right now.
function Editor(game){
this.active = null;
this.moveObject = function(event) {
var x = event.clientX;
var y = event.clientY;
let element = document.elementFromPoint(x, y);
if (element.classList.contains('editorMoveable')) {
do {
element = element.parentElement;
if (element.classList.contains('gameObject'))
break;
} while(element.tagName != "body");
}
this.activeElement = element;
var key = splitElementID(this.activeElement.id);
this.active = this.game.objects[key.object][key.subObject];
let shiftX = event.clientX - this.activeElement.getBoundingClientRect().left;
let shiftY = event.clientY - this.activeElement.getBoundingClientRect().top;
var globalTransform = this.game.calculateGlobals(this.active);
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
function moveAt(pageX, pageY) {
var newPosX = ((pageX - shiftX)/remSize - globalTransform.position.x);
var newPosY = ((pageY - shiftY)/remSize - globalTransform.position.y);
var newRotX = (0);
var newRotY = (0);
var newSclX = (1);
var newSclY = (1);
return {"newPosX": newPosX, "newPosY": newPosY}
}
function onMouseMove(event) {
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
this.activeElement = null;
this.active = null;
}
// Move the elem on mousemove
document.addEventListener('mousemove', onMouseMove.bind(this));
document.addEventListener('mouseup', onMouseUp.bind(this));
};
};
Results are as explained in the upper problem. Since the event is not being removed (they stack on each click) I get "cannot read property of null".
Thanks for all the help in advance!
The problem is that onMouseMove is not the same function as onMouseMove.bind(this).
What you can do is assign that to a variable, and then use that variable in both the addEventListener and removeEventListener calls.
let thisOnMouseMove = onMouseMove.bind(this);
let thisOnMouseUp = onMouseUp.bind(this);
function onMouseMove(event) {
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
}
function onMouseUp() {
document.removeEventListener('mousemove', thisOnMouseMove);
document.removeEventListener('mouseup', thisOnMouseUp);
this.activeElement = null;
this.active = null;
}
// Move the elem on mousemove
document.addEventListener('mousemove', thisOnMouseMove);
document.addEventListener('mouseup', thisOnMouseUp);

onclick function not being called? - no errors

I'm defining a class Session that is created for every new session.
In window.onload, the Session object has a mouse click event listener , on click, it fires the handler and 1. checks if anchor tag was clicked and saves href 2. saves the x and y of mouse click.
The problem: The function user.onclick is not working. Doesn't call the anchorLinkClickHandler(); OR window.addEventListener i.e. the click event handler that saves x and y. NO ERRORS. I think there is a syntactical issue with the below code.. don't know what. Ideas?
As shown (in window.onload):
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
Here is the full code:
function UserSession(campaignId) {
this.campaignId = campaignId;
var aTagHref = aTagHref;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
// get the position of click - Event Listener Function
this.getPosition = function(el) {
  var xPosition = 0;
  var yPosition = 0;
 
  while (el) {
    if (el.nodeName == "BODY") {
      // deal with browser quirks with body/window/document and page scroll
      var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
      var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
 
      xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
      yPosition += (el.offsetTop - yScrollPos + el.clientTop);
    } else {
      xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
      yPosition += (el.offsetTop - el.scrollTop + el.clientTop)
    }
 
    el = el.offsetParent;
  }
  return {
    x: xPosition,
    y: yPosition,
a: "hahah",
  };
};
// On click handler
this.handleClick = function(event) {
// Return the current element clicked on
var el = event.currentTarget;
// Return the offset values of the element clicked on
var relOffsetValues = getPosition(el);
// Find the true value of x and y by adding the offset and the to clicked value of x and y
var realValueX = (relOffsetValues.x + event.clientX );
var realValueY = (relOffsetValues.y + event.clientY);
// display the x and y of the mouse click
alert("Clicks x:" + realValueX + ", y:" + realValueY);
// alert("clientx:" + event.clientX + ", real valie:" + realValueX);
}
// On click ANCHOR TAGS SAVE THEM
// Anchor Tags - Capture the href of the link clicked
this.anchorLinkClickHandler = function() {
var aTags = document.getElementsByTagName('a');
for (var i = aTags.length - 1; i >= 0; --i) {
aTags[i].onclick = function() {
aTagHref[i] = this.getAttribute("href");
alert(aTagHref);
};
}
}
// END OF CLASS
}
Window.onload function (where everything is called)
window.onload = function() {
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
// SCROLL Event Listener
// Get the x and y of the scroll
window.addEventListener("scroll", function(event) {
// document.getScroll= function(){
var sx, sy;
if(window.pageYOffset!= undefined){
sx = pageXOffset;
sy = pageYOffset;
console.log(sx +" if " + sy);
// return [pageXOffset, pageYOffset];
}
else{
var d= document, r= d.documentElement, b= d.body;
sx= r.scrollLeft || b.scrollLeft || 0;
sy= r.scrollTop || b.scrollTop || 0;
console.log(sx +" else " + sy);
// return [sx, sy];
}
// }
});
};
Take a look at https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick to better understand.
The click event is raised when the user clicks on an element. The click event will occur after the mousedown and mouseup events.
You will have to create a HTML element first and when that element is clicked you have to execute a function that does all the actions you want.
HTML:
<button id="btn">Click me</button>
JavaScript:
document.querySelector("#btn").onclick = function(event) {
// do things here
}

how to drag and drop a <div> across the page

I am developing an web application where I am trying simulate a popup window using tags , for style purpose. I done this with this javascript code:
<script>
function handleClick(url){
document.getElementById("results").style.display = 'block';
document.getElementById("about").innerHTML='<object type="text/html" data="'+url+'" ></object>';
}
function cleanDiv() {
document.getElementById("results").style.display = 'none';
document.getElementById("about").innerHTML=' ';
}
</script>
associated to this html code:
<section class="about" id="results">
<div align="right">Fechar</div>
<div id="about" algin="center"></div>
</section>
and the style is on my css file.
I have almost all what I want, but I wish this "popup window" don't stay fixed in a unique position on the page, and the user could move it around with the mouse.
Someone knows how to make this with javascript/html/css only?
You are looking for the HTML5 draggable attribute and events. Make the element draggable by setting draggable="true" and ondragstart="dragElem(event)". Then write your code in function dragElem(ev) { }. See W3Schools
After more search, I ended with this code, from site http://waseemblog.com/42/movable-div-using-javascript.html
html:
<section class="about" id="results" style="left: 183px; top: 111px;" onMouseDown="dragStart(event, 'results');">
<div align="right">X</div>
<div id="content" align="center"></div>
</section>
javascript:
function getID(id)
{
return document.getElementById(id);
}
// Global object to hold drag information.
var dragObj = new Object();
function dragStart(event, id) {
var x, y;
dragObj.elNode = getID(id);
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Save starting positions of cursor and element.
dragObj.cursorStartX = x;
dragObj.cursorStartY = y;
dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);
if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0;
// Capture mousemove and mouseup events on the page.
try {
document.attachEvent("onmousemove", dragGo);
document.attachEvent("onmouseup", dragStop);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch (e) {
document.addEventListener("mousemove", dragGo, true);
document.addEventListener("mouseup", dragStop, true);
event.preventDefault();
}
}
function dragGo(event) {
var x, y;
// Get cursor position with respect to the page.
try {
x = window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
y = window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
catch (e) {
x = event.clientX + window.scrollX;
y = event.clientY + window.scrollY;
}
// Move drag element by the same amount the cursor has moved.
var drLeft = (dragObj.elStartLeft + x - dragObj.cursorStartX);
var drTop = (dragObj.elStartTop + y - dragObj.cursorStartY);
if (drLeft > 0)
{
dragObj.elNode.style.left = drLeft + "px";
}
else
{
dragObj.elNode.style.left = "1px";
}
if (drTop > 0)
{
dragObj.elNode.style.top = drTop + "px";
}
else
{
dragObj.elNode.style.top = "1px";
}
try {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
catch(e){
event.preventDefault();
}
}
function dragStop(event) {
// Stop capturing mousemove and mouseup events.
try {
document.detachEvent("onmousemove", dragGo);
document.detachEvent("onmouseup", dragStop);
}
catch (e) {
document.removeEventListener("mousemove", dragGo, true);
document.removeEventListener("mouseup", dragStop, true);
}
}
It can be bigger than your counterpart using jquery, but I guess it works fine in most browsers available today.

Javascript drag and drop code works on div but doesn't work on img

I'm fairly new to JavaScript, so any help would be awesome!
I created this small block of code that let's me grab a div and drag it around. I assign the "dragme" id to the div and all is fine and dandy. The problem is that if I replace that div from my html and put an img element instead (obviously assigning the "dragme" id to the img), things don't work as expected.
When I click to drag the img, it actually moves for about 3 or 4 pixels then it freezes until I lift the mouse button (mouseup).
Is there some property or characteristic that would prevent the img element from acting the same way as the div does?
var isClicked = false;
var startClientX = 0;
var startClientY = 0;
var startLeft = 0;
var startTop = 0;
window.addEventListener("load", addListeners, true);
function addListeners()
{
document.getElementById("dragme").addEventListener("mousedown", mouseIsDown, false);
document.getElementById("dragme").addEventListener("mouseup", mouseIsUp, false);
window.addEventListener("mousemove", moveImage, false);
function mouseIsDown(e)
{
if (isClicked == false)
{
isClicked = true;
startClientX = e.clientX;
startClientY = e.clientY;
startLeft = document.getElementById("dragme").offsetLeft;
startTop = document.getElementById("dragme").offsetTop;
}
}
function mouseIsUp()
{
if (isClicked == true)
{
isClicked = false;
}
}
function moveImage(e)
{
if (isClicked == true)
{
imageLeftDif = e.clientX - startClientX;
imageTopDif = e.clientY - startClientY;
var newLeftPos = (startLeft + imageLeftDif) + "px";
var newTopPos = (startTop + imageTopDif) + "px";
document.getElementById("dragme").style.left = newLeftPos;
document.getElementById("dragme").style.top = newTopPos;
}
}
}
This fixed the problem (answer provided as a comment by syazdani):
I'd venture to say that the built in browser drag and drop for images
is kicking in. Try e.preventDefault and return false in the mousedown
handler. – syazdani Dec 2 '12 at 17:26

Setting mouse coordinates on fireEvent

I'm trying to emulate a mousemove event in a link in IE8, but I'm not sure if it's possible to set the coordinates of the mouse in the event. This is my code so far:
function Handler()
{
var dump = "";
for(var i in event)
{
dump += ("" + i) + " => " + event[i] + "\n";
}
dumper.value = "";
dumper.value = dump;
}
function Init()
{
document.getElementById("link2").attachEvent("onmousemove", function(){Handler();});
}
function Emulate()
{
var evt = document.createEventObject();
evt.x = 10;
evt.y = 10;
document.getElementById("link2").fireEvent("onmousemove", evt);
}
The event is being attached by calling the Init() function onload. When I call Emulate() the coordinates are the actual coordinates of the cursor. Am I doing something wrong or is this just not possible?
OK I just edited my question to reflect my original failing code (the one I posted was messed up). The solution was to set clientX and clientY instead. x and y will automatically get the values assigned to them:
function Emulate()
{
var evt = document.createEventObject();
evt.clientX = 10;
evt.clientY = 10;
document.getElementById("link2").fireEvent("onmousemove", evt);
}

Categories

Resources