Is there a way to know all the events that happened on document in JavaScript, without going through them one by one?
Instead of running through all events and doing this:
document.onDocumentContentLoaded = function(e) {
documentLoaded = true
};
document.onmousewheel = function(e) {
mouseWheel = true;
};
Is there a function I can call last thing in a page that gives me an array of all events that were called on a certain DOM (document in this case)?
$(window).on("beforeunload", function() {
//var events = document.GetAllEvents();
});
Related
The following code actually works, but I don't understand why. How come that when I pass the "event"-parameter to the function zaehle(), the function actually "knows" that it is supposed to react on what happens in the setup function?
I just can't see what connnects the zaehle() and the setup() function or how the parameter that I pass to zaehle() would be involved.
I hope I could make the question clear. If not I'll gladly try to explain it somehow else. It really bugs me and I feel like I can't go on studying until I get it.
<body>
<div id="eins">0</div>
<div id="zwei">0</div>
<div id="drei">0</div>
<div id="vier">0</div>
<div id="funf">0</div>
</body>
JS
var mouseoverZaehler = 0;
function zaehle(event) {
mouseoverZaehler++;
event.target.innerHTML = mouseoverZaehler;
}
function setup() {
document.getElementById("eins").addEventListener("mouseover", zaehle);
document.getElementById("zwei").addEventListener("mouseover", zaehle);
document.getElementById("drei").addEventListener("mouseover", zaehle);
document.getElementById("vier").addEventListener("mouseover", zaehle);
document.getElementById("funf").addEventListener("mouseover", zaehle);
}
window.addEventListener("load", setup);
Here is what happens step by step:
Page loads
setup function is called (because of window.addEventListener("load", setup))
Each element in setup function gets a mouseover event listener attached to it and when it fires zaehle function is called (because of document.getElementById("number").addEventListener("mouseover", zaehle))
You move your mouse over any of the elements
zaehle function gets called - mouseoverZaehler is incremented and innerHTML of the targeted element is set to the updated value of mouseoverZaehler
Check out addEventListener docs for further details.
The addEventListener calls in your setup function tell the browser that when a mouseover event occurs on the relevant element, it should call the function you're giving it (zaehle, in your case). It's the browser that passes the argument to zaehle, later, when calling it.
You could imagine addEventListener, conceptually, as putting that handler function on a list for the event on the element:
// VERY conceptual, leaves out a lot of details
function addEventListener(eventName, handler) {
this.events[eventName].handlers.push(handler);
}
...and then later, when the event occurs, the browser creates an event object and calls those handlers:
// Again, VERY conceptual, leaves out a lot of details
var event = /*...*/;
element.events[eventName].handlers.forEach(function(handler) {
handler.call(element, event);
});
Here's a working analogue of what's going on:
function FakeElement () {
this.events = Object.create(null);
}
FakeElement.prototype.addEventListener = function(eventName, handler) {
var eventEntry = this.events[eventName];
if (!eventEntry) {
eventEntry = this.events[eventName] = {
handlers: []
};
}
eventEntry.handlers.push(handler);
};
FakeElement.prototype.trigger = function(eventName) {
var event = {type: eventName}; // "Browser" creates the event
var eventEntry = this.events[eventName];
var handlers = eventEntry && eventEntry.handlers;
if (handlers) {
handlers.forEach(function(handler) {
handler.call(this, event); // "Browser" calls handler, passing
}); // the event into it
}
};
// Using it:
function zaehle(event) {
console.log("zaehle got event: " + event.type);
}
var e = new FakeElement();
e.addEventListener("mouseover", zaehle);
console.log("added handler for mouseover to element");
// Simulate the event occurring
var timer = setInterval(function() {
e.trigger("mouseover");
}, 500);
setTimeout(function() {
clearInterval(timer);
}, 3000);
You have registered your callback/function zaehle() for mouseover event. So when that event occurs for a specific div, browser calls the callback with event object which contains information about the event and the target i.e event occurred on which element.
I am trying to add certain javascript files on an event, say click. I am trying to use the Javascript to be used on same event, only if it is triggered. This is because the scripts are slowing down the page load and there is no need for the scripts otherwise.
Can I just move the scripts to the footer and be all set, or do this pro grammatically via loading them only when needed - via event triggering instead? Below is what I have so far:
HTML:
<a id="customId" href="#myLink"></a>
Javascript:
$(document).ready(function() {
//The async addition
var myJS = {
lazyload : function(scriptSrc) {
if(!this.isPresent(scriptSrc)){
var scriptTag = document.createElement('script');
scriptTag.src = scriptSrc;
scriptTag.async = true;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
return false;
}
};
//The event trigger needs to do something using the said script
if($('#customId')){
//Approach 1:
var mapEl = document.getElementById("customId");
mapEl.addEventListener("click", customEventHandler, false);
//mapEl.dispatchEvent(event);
//*where
customEventHandler : function(e){
e.preventDefault;
myJS.lazyload('/jsfile.js');
// Update or use link relative #href (not complete path) and use the javascript without navigating out of page.
//e.currentTarget.dispatchEvent(?);
}
//2nd attempt: Adds the script, but not able to trigger event to use JS
$('#customId').click(function(event) {
event.preventDefault();
myJS.lazyload('/jsfile.js');
//Either approach:
//Trigger the custom event to do an actual click after doing the lazy load, using the JS file
(click); $('#customId').trigger('click'); //Is this correct on same element ID
});
}
}
Try using onload event of script element, defining a custom event to prevent recursively calling native click event handler on element
$(document).ready(function() {
//The async addition
var myJS = {
lazyload: function(scriptSrc, id, type) {
// use `.is()` to check if `script` element has `src`
// equal to `scriptSrc`
if (!$("script[src='"+ scriptSrc +"']").is("*")) {
var scriptTag = document.createElement("script");
scriptTag.src = scriptSrc;
scriptTag.async = true;
// use `script` `onload` to trigger custom event `customClick`
scriptTag.onload = function() {
$(id).trigger(type)
};
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
return false;
}
};
$("#customId").on("click", function() {
myJS.lazyload("jsfile.js", "#" + this.id, "customClick");
})
// do stuff at `customClick` event
.one("customClick", function(e) {
customClick(e.type)
});
});
plnkr http://plnkr.co/edit/Rw4BRAfSYlXXe5c6IUml?p=preview
JavaScript touch events contain properties for radius and force. Unfortunately it appears that events aren't generated when either property changes. Events are only triggered for things like touch start, move or end. Can anyone think of a way to get more updates on change of touch size?
Currently to get radius updates I have to wiggle my finger to trigger the touch move event, but I would prefer a software solution.
I had the same issue and then discovered this blog post: http://blog.framerjs.com/posts/prototyping-3D-touch-interactions.html
In a nutshell, we need to use touchstart event to capture the touch event, assign the event to a variable and then use setInterval to get the force value:
var el = document.getElementById('myElement');
var currTouch = null;
var currTouchInterval = null;
attachListeners = function () {
el.addEventListener('touchstart', enterForceTouch, false);
el.addEventListener('touchend', exitForceTouch, false);
}
enterForceTouch = function (evt) {
evt.preventDefault();
currTouch = evt;
currTouchInterval = setInterval(updateForceTouch, 10); // 100 times per second.
}
updateForceTouch = function() {
if (currTouch) {
console.log(currTouch.touches[0].force); // Log our current force value.
}
}
exitForceTouch = function (evt) {
evt.preventDefault();
currTouch = null;
clearInterval(currTouchInterval);
}
attachListeners();
Is there a way to add an event listener to a MediaElementPlayer object after it's initialized? I would like to add listeners incrementally, as needed, instead of re-creating the player each time I need to add a new listener. For example:
var mejsplayer = new MediaElementPlayer($("#mejsplayer"), mejsOptions);
// Keep track of added event listeners
var addedListeners = {};
function addEventListener(eventType, func) {
if (addedListeners[eventType]) return;
console.log("Adding listener " + eventType);
addedListeners[eventType] = func;
mejsplayer.addEventListener(eventType, func, false);
};
If that's not possible I'd like some feedback on if it really is such a bad thing to re-create the player object each time, setting the listeners with the mejsOptions.success(mediaElement, domObject) function.
As said on your other question about accessing the MeJS properties, you can use the DOM element to achieve this:
$('#mejsplayer').bind('playing', function(e) {
console.log('bind - playing');
});
var player = document.getElementById('mejsplayer');
player.addEventListener('playing', function(e) {
console.log('addEventListener - playing');
});
I can't figure out how to do it. It would seem to be something like this:
function MyObject() {
this.fireEvent("myEvent");
}
And then in a separate JavaScript file:
var obj = new MyObject();
obj.addEventListener("myEvent", function() {
alert("Event Fired");
});
But of course it doesn't work. My question is, how would I go about doing something like that?
In your example, you're firing the event immediately in the constructor (before the event listener is attached). Try moving the firing logic into a separate function.
Update:
Also, it seems like you're not firing an event properly. See this article for more information on how to properly fire events in a cross-browser manner. From that article:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}