Create mouse event for Mozilla - javascript

I am creating mouse event by drag and drop. It works for Chrome and Opera but i have problem with doing it in Mozilla. It writes me, that event is not define.
document.getElementById("cievka").src = "cievka.png";
document.getElementById("cievka").width = "65";
document.getElementById("cievka").height = "10";
document.getElementById("cievka").draggable = "true";
document.getElementById("cievka").addEventListener('dragstart', function() {
drag(this, event);
}, false);
function drag(target, ev) {
ev.dataTransfer.setData('img', target.id);
}

event isn't global in Firefox.
Use the following:
document.getElementById("cievka").addEventListener('dragstart', function(event) {
drag(this, event);
}, false);

Firefox the event is passed to handler as a parameter. You would need to handle event variable here.
function fName(e)
{
e = e||window.event;
}
Its typical cross browser stuff

Related

JavaScript Module pattern and Drag and Drop API

I have a sample module in js that is suppose to manage Drag and Drop file upload.
The code seems to work for 'dragenter' event function but when I drop the file, and 'drop' event should call the dropped function, the code always forwards to the file path.
Here is the code sample
var testModule = (function testBuilder(){
function call(evt) {
evt.preventDefault();
console.log('works');
}
function dropped(evt) {
evt.preventDefault();
console.log('file dropped');
}
var element = document.getElementById('testBlock');
function init() {
element.addEventListener('dragenter', call, false);
element.addEventListener('drop', dropped, false);
}
publicAPI = {
init: init
};
return publicAPI;
})();
window.onload = function() {
testModule.init();
};
and a jsbin here https://jsbin.com/redixucate/edit?js,console,output
If anyone can figure out why it keeps redirecting the file path, I would rly appreciate it.
Add 'dragover' event with preventDefault and it should work.
Inside your init():
element.addEventListener('dragover', over, false);
and over function:
function over(e) {
e = e || window.event;
if(e.preventDefault) {
e.preventDefault();
}
}
Also add the same prevention to your other two functions ..
See https://jsbin.com/xemovariwu/1/edit?js,console,output
Also see this question/answer.

Call function once from multiple events

I've been working on webpages for a range of touch screen devices, and one of the most consistent problems is how touch events are handled.
Is there a nice way to only call a function once even when multiple (roughly) simultaneous events call it?
e.g.
$("body").on("mousedown touchstart MSPointerDown", function () {
alert("This message will appear multiple times on some devices.");
})
I've thought about using a timeout so the function can only be called once every 200 milliseconds or something similar (off the top of my head and untested):
var allowed = true;
$("body").on("mousedown touchstart MSPointerDown", function () {
if(allowed){
allowed = false;
alert("This message will hopefully only appear once!");
setTimeout(function () { allowed = true }, 200);
}
})
(For this question, I am NOT looking for plugin suggestions, I am aware there are lots of touch event plugins)
Is there a proper/nicer way to use multiple events as possible triggers for a single function? Could I alias the events in some way without breaking their other uses?
In effect, you're looking to take only the first event type that comes through and ignore all the others. This will still fire for future clicks/touches. Enter closures.
$(document).ready(function() {
function alertClosure() {
var eventType = null;
function doAlert(e) {
if (!eventType) {
eventType = e.type; // only the first eventType we get will be registered
}
if (e.type == eventType) {
alert("This message will hopefully only appear once!: " + e.type);
}
}
return doAlert;
}
$("body").on( "mousedown touchstart MSPointerDown", alertClosure() );
});
http://plnkr.co/edit/oz48d3
You could use $.one (rather than $.on)
Here : $.one documentation on jquery.com
If you want it to be subsequently called then you could rebind the handler on a timeout, something like this:
function handler(){
var called = false;
return function(ev){
if(!called){
called = true;
$("ul#messages").append($("<li>").text("event"));
setTimeout(bind, 1000); // rebind after a suitable pause
}
}
}
function bind(){
$("ul#messages").one("click", new handler())
};
$(function(){
bind();
});
https://jsfiddle.net/p3t6xo48/5/
This allows each bound handler to be run once, and once only, for multiple events, then it's rebound after a suitable pause.

Get the contents of a particular tab (Firefox add-on development) [duplicate]

This question already has answers here:
Firefox add-on get the tab body content
(3 answers)
Closed 8 years ago.
I'm working on a Firefox add-on, and with it, I need to monitor the contents of a particular site and react to DOM changes. Currently, I'm using a combination of gBrowser.contentDocument.getElementsByClassName("class") and attaching a DOMSubteeeModified event to it. But I notice that it works only when the tab is active. When I'm away using another tab, and the DOM changes in the inactive tab, it does not work. How do I get around this? The Firefox MDN is pretty scattered (and sometimes outdated), it is very frustrating for a newbie.
Here is a simplified version of what I'm doing:
var MyExtension = {
init() : function() {
if("gBrowser" in window) {
gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
},
onPageLoad: function(e) {
var doc = e.originalTarget;
if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
MyExtension.XXX.handler(e);
}
e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
},
onUnload: function(e) {
if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
//remove listeners and nullify references to dom objects
}
};
MyExtension.XXX = {
handler : function(e) {
//get dom element with gBrowser.contentDocument.getElementsByClassName("class");
//bind DOMSubtreeModified listener, attach a function to handle the event
}
};
window.addEventListener("load", function(e) {
window.removeEventListener("load", load, false);
MyExtension.init();
}, false);
Here's the technique I'm following, using gBrowser.selectedBrowser as documented here
var MyExtension = {
tab : null, //<---- added this line
init() : function() {
if("gBrowser" in window) {
gBrowser.addEventListener("DOMContentLoaded", function(e){this.onPageLoad(e);},false);
},
onPageLoad: function(e) {
var doc = e.originalTarget;
if((/http://xxxx.xyz/v/[0-9a-z]/).test(doc.location.href)) {
this.tab = gBrowser.selectedBrowser; //<--- GET REFERENCE TO CURRENT TAB
MyExtension.XXX.handler(e);
}
e.originalTarget.defaultView.addEventListener("unload", function(e){MyExtension.onUnload(e);}, false);
},
onUnload: function(e) {
if((/http://xxxx.xyz/v/[0-9a-z]/).test(e.originalTarget.location.href)) {
//remove listeners and nullify references to dom objects
}
};
MyExtension.XXX = {
handler : function(e) {
//get dom element
MyExtension.tab.contentDocument.getElementsByClassName("class"); //<--- GET CONTENT DOCUMENT INSIDE DESIRED TAB
//bind DOMSubtreeModified listener, attach a function to handle the event
}
};

FireFox different onchange behavior than Webkit/IE

Is anyone able to explain this?
Basically when you're in firefox, and you hit tab, the "console.log" in the onchange gets called but not in Chrome/Safari (webkit) or IE.
function initLookup(id) {
var lookupElement = document.getElementById(id);
var lookup = new Lookup(lookupElement);
lookupElement.lookup = lookup;
}
function Lookup(lookupElement) {
this.doKeyDown = doKeyDown;
this.setLookup = setLookup;
this.inputElement = lookupElement;
this.inputElement.onkeydown = this.doKeyDown;
var self = this;
function setLookup() {
self.inputElement.value = 'asdf';
}
function doKeyDown(event) {
if(event.keyCode == 9) {
setLookup();
}
}
}
initLookup("one");
And a JS fiddle working example:​
http://jsfiddle.net/pj9Gf/5/
Gecko differs from IE (and apparently Webkit), in that the change event is fired after the blur event had been fired.
By setting the value on TAB key-press, you're effectively preventing the change from being applied, as the change trigger is defined by a difference between the values detected on focus and on blur.
Reference
element.onchange on Mozilla Developer Network

Is it possible to listen for keydown and keyup while resizing window

I'm trying to detect keydown and keyup, while the window is being resized. What I've tried so far, only fires the key events after the resize is finished.
$(window).resize(function(){
console.log("resizing");
});
$(window).keydown(function(e){
$("#key").css("background","green");
});
$(window).keyup(function(e){
$("#key").css("background","red");
});
Okay, so part of the problem you may be running into here is that keydown isn't an on or off thing, it's a fire-constantly thing.
The same is true of onresize.
As you resize the window the event gets called over and over.
Also, because JS isn't multithreaded, only one of these events is going to happen at one time.
The other event is going to be queued up to run immediately after the other event finishes.
So what you actually want is a state machine that one event sets, and the other event checks.
Quick examples:
var BrowserWindow = { width : 0, height : 0, prevWidth : 0, prevHeight : 0 };
window.onresize = function (e) {
/* set prevWidth/prevHeight, get new width/height */
};
window.onkeydown = function (e) {
if (BrowserWindow.prevWidth !== BrowserWindow.width) { /*...*/ }
};
That would work (except that it would only work when the screen was actively being stretched... so it wouldn't happen in the case where the key was down and the edge of the window was being held but not dragged (which might lead to flickering if the browser fires keydown events more-frequently than resize).
The more appropriate answer would likely be to go the other way:
var Keyboard = {
currentKeys : {},
previousKeys : {}
};
window.onkeydown = function (e) { Keyboard.currentKeys[e.keyCode] = true; };
window.onkeyup = function (e) { delete Keyboard.currentKeys[e.keyCode]; };
window.onresize = function (e) {
var key = <X>,
state = "";
state = Keyboard.currentKeys[key] && !Keyboard.previousKeys[key]
? "pressed"
: !Keyboard.currentKeys[key] && Keyboard.previousKeys[key]
? "released"
: Keyboard.currentKeys[key] && Keyboard.previousKeys[key]
? "held"
: "off";
Keyboard.previousKeys = Keyboard.currentKeys;
doSomething(state);
};
This is less than perfect from an architecture standpoint, but is more along the idea of what you'd have to do in another environment.

Categories

Resources