Javascript Create Custom Event - javascript

I am making a Tampermonkey script, and I want to create an event listener to listen for when a video's width is changed, specifically when a video is made full-screen. This is what I have right now:
var htmlVideos = document.getElementsByTagName('video');
function checkVidWidth() {
for (i = 0; i < htmlVideos.length; i++) {
if ($(htmlVideos[i]).width() != vidWidths[i]) {
vidWidths[i] = $(htmlVideos[i]).width();
checkVidChange(true);
return;
}
}
}
setInterval(checkVidWidth, 3);
vidWidths is an array defined elsewhere of the prior widths of the video. But I don't want to use setInterval I want to make an event that occurs when $(htmlVideos[i]).width() changes.

These events already exist - there's no need to build your own logic to achieve this, and certainly not by running your code every 3ms.
You can use the fullscreenchange event, like this using jQuery:
$('video').on('fullscreenchange webkitfullscreenchange mozfullscreenchange', function(e) {
var videoIsFullScreen = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
if (videoIsFullScreen) {
// video is full screen, do something...
}
else {
// video was full screen, has now been restored to default size
}
});
Note that I also bound the webkit and moz variations of the event for full compatibility.

You can use fullscreen change event to detect fullscreen :
$(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange',
And use resize evet to detect width change
$('#video').resize(function() {
});
EDIT
Resize event CAN be applied on elements other than the window using jquery, check this example.

Related

how to attach an event listener to the DOM, depending upon the screen size

for eg:document.body.addEventListener('wheel', foo, {passive: true});
This should be dynamically added/removed if the screen size is above 500px
As #Rounin says, window.matchMedia is the equivalent of CSS #media queries. But the coolest part is not just that you can check with .matches -- the awesome thing is that you can add an event-listener that gets fired when the state changes.
You want something to happen when the screen width transition to above or below 500px -- you want to add a mouse wheel listener when the screen is >500px and remove it when the screen is <500px
You will also have to check for .matches initially to decide whether to add the listener or not when your page first loads, as #Rounin shows, but then the listener can be added and removed automatically based on matching the media query.
let widthMatch = window.matchMedia("(min-width: 500px)");
// mm in the function arg is the matchMedia object, passed back into the function
widthMatch.addEventListener('change', function(mm) {
if (mm.matches) {
// it matches the media query: that is, min-width is >= 500px
document.body.addEventListener( etc. );
}
else {
// it no longer matches the media query
// remove the event listener
}
});
how to attach an event listener to the DOM [...] only if the screen
size is above 500px
window.matchMedia is the javascript equivalent of CSS #media queries.
For example, the following code verifies that the screen width is above 500px.
var widerScreenWidth = window.matchMedia("(min-width: 501px)");
if (widerScreenWidth.matches) {
// [... YOUR CODE HERE...]
}
you have 3 options:
check the window size on load and add the listener if > 500: easiest solution but will not adjust if the user resizes the window.
add a listener to window resize and every time the width changes add or remove the 'wheel' event listener depending on the width.
always add an event listener to 'wheel', but inside the event callback, check for the width every time the callback runs before executing your logic
function getScreenWidth() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0]
return w.innerWidth || e.clientWidth || g.clientWidth
}
function wheelListener() {
console.log(getScreenWidth())
}
window.onresize = function() {
if (getScreenWidth() > 500) {
document.body.addEventListener('wheel', wheelListener, {passive: true})
} else {
document.body.removeEventListener('wheel', wheelListener)
}
}
// to apply when the window loaded
window.onresize()

Fire jQuery when breakpoint is reached

I have a responsive design with multiple breakpoints. Some of the block dimensions in the content are calculated with jQuery. When the viewport changes these dimensions change thus the calculation should be run. How can I fire these events when the dimension of the reference element changes? The reference element changes when a breakpoint is crossed.
I've looked at the "orientationchange" event but it's not having the results I need.
You provide very little specifics and no code so all we can do is answer very generally.
Usually, you install a .resize() event handler and on every resize of the containing window, you check to see if the resulting dimensions have changed such that you need to recalculate and modify the layout.
$(window).resize(function(e) {
// check dimensions here to decide if layout needs to be adjusted
});
jQuery mobile supports the orientationchange event like this which also gives you e.orientation as "portrait" or "landscape":
$(window).on( "orientationchange", function(e) {
// check dimensions here to decide if layout needs to be adjusted
});
There are no DOM events for watching a size change on a specific element in the page other than a window object. Instead, you have to watch whatever other events might cause a given element to get resized which might be a resize of the window, an orientation change or some other action in the page that modifies the page (a button press or click on something, for example). Then, when those other events fire and get processed, you can then check the size of your target element and see if it changed.
Here's a jQuery plugin that debounces the resize event so it only tells you about a resize when the size has stopped changing:
(function($) {
var uniqueCntr = 0;
$.fn.resized = function (waitTime, fn) {
if (typeof waitTime === "function") {
fn = waitTime;
waitTime = 250;
}
var tag = "resizeTimer" + uniqueCntr++;
this.resize(function () {
var self = $(this);
var timer = self.data(tag);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
self.removeData(tag);
fn.call(self[0]);
}, waitTime);
self.data(tag, timer);
});
}
})(jQuery);
Working demo: https://jsfiddle.net/jfriend00/k415qunp/
Sample usage:
$(window).resized(function() {
// put code here to act when window stopped getting resized
});
This page might help you. They talk about JS execution based on breakpoints and doing it with cross-browser support. Basically you'll be using a hidden pseudo element using the "content" property of .myClass:after.

How to detect the dragleave event in Firefox when dragging outside the window

Firefox doesn't properly trigger the dragleave event when dragging outside of the window:
https://bugzilla.mozilla.org/show_bug.cgi?id=665704
https://bugzilla.mozilla.org/show_bug.cgi?id=656164
I'm trying to develop a workaround for this (which I know is possible because Gmail is doing it), but the only thing I can come up with seems really hackish.
One way of knowing when dragging outside the window has occurred it to wait for the dragover event to stop firing (because dragover fires constantly during a drag and drop operation). Here's how I'm doing that:
var timeout;
function dragleaveFunctionality() {
// do stuff
}
function firefoxTimeoutHack() {
clearTimeout(timeout);
timeout = setTimeout(dragleaveFunctionality, 200);
}
$(document).on('dragover', firefoxTimeoutHack);
This code is essentially creating and clearing a timeout over and over again. The 200 millisecond timeout will not be reached unless the dragover event stops firing.
While this works, I don't like the idea of using a timeout for this purpose. It feels wrong. It also means there's a slight lag before the "dropzone" styling goes away.
The other idea I had was to detect when the mouse leaves the window, but the normal ways of doing that don't seem to work during drag and drop operations.
Does anyone out there have a better way of doing this?
UPDATE:
Here's the code I am using:
$(function() {
var counter = 0;
$(document).on('dragenter', function(e) {
counter += 1;
console.log(counter, e.target);
});
$(document).on('dragleave', function(e) {
counter -= 1;
console.log(counter, e.target);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Open up the console and look at what number is reporting when dragging files in and out of the window. The number should always be 0 when leaving the window, but in Firefox it's not.</p>
I've found a solution. The problem was not so much that the dragleave event wasn't firing; rather, the dragenter event was firing twice when first dragging a file into the window (and additionally sometimes when dragging over certain elements). My original solution was to use a counter to track when the final dragleave event was occuring, but the double firing of dragenter events was messing up the count. (Why couldn't I just listen for dragleave you ask? Well, because dragleave functions very similarly to mouseout in that it fires not only when leaving the element but also when entering a child element. Thus, when dragleave fires, your mouse may very well still be within the bounds of the original element.)
The solution I came up with was to keep track of which elements dragenter and dragleave had been triggered on. Since events propagate up to the document, listening for dragenter and dragleave on a particular element will capture not only events on that element but also events on its children.
So, I created a jQuery collection $() to keep track of what events were fired on what elements. I added the event.target to the collection whenever dragenter was fired, and I removed event.target from the collection whenever dragleave happened. The idea was that if the collection were empty it would mean I had actually left the original element because if I were entering a child element instead, at least one element (the child) would still be in the jQuery collection. Lastly, when the drop event is fired, I want to reset the collection to empty, so it's ready to go when the next dragenter event occurs.
jQuery also saves a lot of extra work because it automatically does duplicate checking, so event.target doesn't get added twice, even when Firefox was incorrectly double-invoking dragenter.
Phew, anyway, here's a basic version of the code I ended up using. I've put it into a simple jQuery plugin if anyone else is interested in using it. Basically, you call .draghover on any element, and draghoverstart is triggered when first dragging into the element, and draghoverend is triggered once the drag has actually left it.
// The plugin code
$.fn.draghover = function(options) {
return this.each(function() {
var collection = $(),
self = $(this);
self.on('dragenter', function(e) {
if (collection.length === 0) {
self.trigger('draghoverstart');
}
collection = collection.add(e.target);
});
self.on('dragleave drop', function(e) {
collection = collection.not(e.target);
if (collection.length === 0) {
self.trigger('draghoverend');
}
});
});
};
// Now that we have a plugin, we can listen for the new events
$(window).draghover().on({
'draghoverstart': function() {
console.log('A file has been dragged into the window.');
},
'draghoverend': function() {
console.log('A file has been dragged out of window.');
}
});
Without jQuery
To handle this without jQuery you can do something like this:
// I want to handle drag leaving on the document
let count = 0
onDragEnter = (event) => {
if (event.currentTarget === document) {
count += 1
}
}
onDragLeave = (event) => {
if (event.currentTarget === document) {
count += 0
}
if (count === 0) {
// Handle drag leave.
}
}
Depending on what you wish to accomplish you can get around this issue by using the :-moz-drag-over pseudo-class that is only available in Firefox which lets you react to a file being dragged over an element.
Take a look at this simple demo http://codepen.io/ryanseddon/pen/Ccsua
.dragover {
background: red;
width: 500px;
height: 300px;
}
.dragover:-moz-drag-over {
background: green;
}
Inspired by #PhilipWalton 's code, I simplified the jQuery plugin code.
$.fn.draghover = function(fnIn, fnOut) {
return this.each(function() {
var n = 0;
$(this).on('dragenter', function(e) {
(++n, n==1) && fnIn && fnIn.call(this, e);
}).on('dragleave drop', function(e) {
(--n, n==0) && fnOut && fnOut.call(this, e);
});
});
};
Now you can use the jquery plugin like jquery hover method:
// Testing code 1
$(window).draghover(function() {
console.log('into window');
}, function() {
console.log('out of window');
});
// Testing code 2
$('#d1').draghover(function() {
console.log('into #d1');
}, function() {
console.log('out of #d1');
});
only solution that has worked for me and took me a few goes hope this helps someone!
note when cloning you need to deepclone with events and data:
HTML:
<div class="dropbox"><p>Child element still works!</p></div>
<div class="dropbox"></div>
<div class="dropbox"></div>
jQuery
$('.dropbox').each(function(idx, el){
$(this).data("counter" , 0);
});
$('.dropbox').clone(true,true).appendTo($('body');
$('dropbox').on({
dragenter : function(e){
$(this).data().counter++;
<!-- YOUR CODE HERE -->
},
dragleave: function(e){
$(this).data().counter--;
if($(this).data().counter === 0)
<!-- THEN RUN YOUR CODE HERE -->
}
});
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
// for now we can just use an alert
alert("left window");
}
});
This is copied from How can I detect when the mouse leaves the window?. addEvent is just crossbrowser addEventListener.

Route events from one dom node to another WITHOUT JQUERY

My question is totally like: How do I pass javascript events from one element to another? except for the fact that I need a raw JS solution.
I've got a webos app whose UI features a layering of elements that scroll in conjunction with eachother on a page. Basically I have what amounts to an iframe (not quite, but in principle), and a floating header that lives in a z-layer above it. When I scroll the elements in the iframe, it also moves the floating header up.
However, I also need to scroll the underlying doc when the header is dragged.
This is a touchscreen interface, so I'm trying onmousemove and ontouchmove events.
I've got the following code, but it doesn't seem to do anything:
setupScrollFromHeader: function setupScrollFromHeader() {
// webos enyo stuff. Don't worry about it. just know that I get the
// raw dom elements through the this.$.elem.node syntax
var body = this.$.body, header = this.$.mailHeaderUnit;
if (!header.hasNode() && !body.hasNode()) {
return;
}
body = body.node;
// end enyo specific stuff
header.node.addEventListener('touchmove', function(event) {
console.log("### touch move");
event.preventDefault();
body.dispatchEvent(event);
var touch = event.touches[0];
console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
}, true);
console.log("### set this stuff up");
}
I'm using dispatchEvent to forward the event, per:
https://developer.mozilla.org/en/DOM/element.dispatchEvent
I've tried this with either touchmove and mousemove events by themselves, toggling prevent default, and also changing the bubbling behavior with the true/false flags.
In all cases I see the log print out, but the events are never passed to the underlying element. What am I doing wrong? Is it even possible to pass the events around this way?
So this is the right way to route events. Looks like the widget I'm talking to needed a mousedown event before receiving the touchmove events. For maximum compatibility, I added listeners for both mouse and touch, for testing in browser and on device.
I came up with the following:
setupScrollFromHeader: function setupScrollFromHeader() {
if (setupScrollFromHeader.complete) {
return;
}
var body = this.$.body, header = this.$.mailHeaderUnit;
if (!header.hasNode() && !body.hasNode()) {
return;
}
var header = header.node;
var forwarder = function forwarder(event) {
body.$.view.node.dispatchEvent(event);
};
['mousedown', 'mousemove', 'touchstart', 'touchmove', 'touchend'].forEach(function(key) {
header.addEventListener(key, forwarder, true);
});
setupScrollFromHeader.complete = true;
},
In the general browser case, you can test such forwarding with with two buttons, routing the click event from one to the other works as expected through dispatchEvent(...).
ie:
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function(event) {
button2.dispatchEvent(event);
}, true);
button2.addEventListener('click', function(event) {
alert("Magnets. How do they work?");
}, true);
clicking button1 will fire the handler of button2.

iOS Web App touch gestures

I've searched all across the web to find a simple way of adding touch gestures to a simple button. Basically I'm trying to find a simple way of getting the back button (which you usually see on the task-bar at the top of an iOS device) to change CSS classes from 'normal' state to 'pressed' state when pressed.
Although I'm very new to Javascript, I would prefer to use standard DOM methods rather than jQuery (or any other library). Would anyone have some complete code and explain how the JavaScript code reads an ontouchstart and ontouchend event and how these functions could be used to change CSS classes?
Any help would be greatly appreciated!
TC
ontouchstart, ontouchmove and ontouchend are managed the same as onclick, onmousemove and so.
You can apply the listeners in a <script> tag or directly in the html element.
Using JavaScript only
var back = document.getElementById("back-button-id");
back.ontouchstart = function( event ) {
// using the target property of the event
// you can reach the hitted html element
event.target.className = 'css-href-selected-class-name';
}
back.ontouchend = function( event ) {
event.target.className = 'css-href-normal-class-name';
}
Using HTML tag and callbacks
1) Declare your Javascript callbacks to swap a css class for any state
function onclickCallback( event ) {
// do something
}
function ontouchstartCallback( event ) {
event.target.className = 'selected';
}
function ontouchendCallback( event ) {
event.target.className = 'normal';
}
2) Put the callbacks into the anchor tag (I suggest to use DIV instead of A)
<div class="normal" onclick="onclickCallback( event );" ontouchstart="ontouchstartCallback( event );" ontouchend="ontouchendCallback( event );">Back</div>
Edit 1: to prevent hilight freezing during scrolling
Try to add the ontouchmove handler
ontouchmove="ontouchmoveCallback( event );"
Then declare the handler function that swap the css class
function ontouchmoveCallback( event ) {
event.target.className = 'normal';
}
Hope this helps!
Ciao.
This should get you started:
HTML:
<input type="button" id="thebutton" value="Do Stuff!" />
Javascript:
var thebutton = document.getElementById("thebutton");
thebutton.ontouchstart = function(e)
{
this.setAttribute('class', 'pressed');
var touches = e.touches; // array of all touch data
var target = touches[0].target; // what DOM element was touched
var pageX = touches[0].pageX; // coords relative to site
var pageY = touches[0].pageY;
var clientX = touches[0].clientX; // coords relative to screen
var clientY = touches[0].clientY;
};
thebutton.ontouchmove = function(e)
{
var touches = e.touches; // same fields as above
var changedTouches = e.changedTouches; // only touches which have changed
};
thebutton.ontouchend = function(e)
{
this.setAttribute('class', '');
// cleanup, if needed
};
For more details, see: http://sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
It's worth noting that MobileSafari sometimes does wonky things with touch events and form elements (input boxes in particular). You may find it's better to use a styled div than an actual input button.
EDIT: For what you're trying to do, I think you might be better served with simple click events, which generally work fine for things like button presses. Touch events are more for drag and drop, precise finger tracking etc. Try this:
thebutton.onclick = function(e) { this.setAttribute('class', 'your_class'); };
EDIT2: Now I see what you're asking for. Easiest way is this:
thebutton.ontouchstart = function(e) { this.setAttribute('class', 'pressed'); };
thebutton.ontouchend = function(e) { this.setAttribute('class', ''); };
There are a couple of libraries already for jQuery
http://plugins.jquery.com/project/multiswipe
And you also can check this demo from
http://taitems.github.com/Mobile-Web-based-Gesture-Recognition/
And you can fork the example and start working with it.
There are some options but everything its quite new.

Categories