Javascript recording and repeating touch events - javascript

I am trying to record and repeating touches programmatically. All my efforts have failed. What is wrong?
var elm = null, begin = true, touches = [];
$(document).ready(function () {
elm = $('#element');
elm.bind('touchstart touchmove touchend touchcancel', function (e) {
if (begin) {
touches.push(e);
if (e.type == 'touchend') {
begin = false;
start();
}
}
});
});
function start() {
setTimeout(function () {
try {
for (var e in touches) elm.dispatchEvent(e);
// elm.trigger(e.type, e);
} catch (e) {
console.log(e);
}
start();
}, 5000);
}
Thanks in advance.

Related

Javascript - Remove event listener at resize

I'm doing some work to make navigation fully accessible by mouse over, keyboard and click, depending on the resolution.
I am looking for that in mobile, only the click works. And hover, click, keyboard for higher resolutions.
Important edit :
It only works perfectly when I load the page at the correct resolution (low or high). BUT, if I resize live, the removeEventListener doesn't work.
Plus : I don't know if my stopImmediatePropagation is the better solution to avoid multiple functions.
Here is the idea of the code.
JS
window.addEventListener("DOMContentLoaded", onLoadFunction);
function onLoadFunction(e) {
menu_burger();
onResizeFunction(); //trigger resize function immediately
window.addEventListener("resize", onResizeFunction);
}
function onResizeFunction(e) {
if (window.innerWidth > 770) {
window.removeEventListener('resize', menu_onClick);
menu_onClick();
menu_mouseOver();
menu_onFocus();
menu_onFocusDetection();
} else {
window.removeEventListener('resize', menu_onClick);
window.removeEventListener('resize', menu_mouseOver);
window.removeEventListener('resize', menu_onFocusDetection);
window.removeEventListener('resize', menu_onFocus);
menu_onClick();
}
}
// FONCTIONS MENU
const focusDetectionEntry = document.querySelectorAll('.nav-list--focus-detection > li[aria-expanded] > button');
const focusEntry = document.querySelectorAll('.nav-list--focus > li[aria-expanded] > button');
const overEntry = document.querySelectorAll('.nav-list--over > li[aria-expanded] > button');
const clickEntry = document.querySelectorAll('.nav-list--click > li[aria-expanded] > button');
function menu_burger() {
document.querySelector('.menu-burger').addEventListener('click', function () {
this.classList.toggle('menu--open');
document.querySelector('.main-nav-list').classList.toggle('main-nav-list--open');
});
}
function menu_mouseOver() {
overEntry.forEach(sub => {
var subParent = sub.parentElement;
subParent.addEventListener('mouseover', function(e) {
subParent.setAttribute('aria-expanded', 'true');
console.log('OVER IN');
e.stopImmediatePropagation();
});
subParent.addEventListener('mouseout', function(e) {
subParent.setAttribute('aria-expanded', 'false');
console.log('OVER OUT');
e.stopImmediatePropagation();
});
})
}
function menu_onClick() {
clickEntry.forEach(sub => {
var subParent = sub.parentElement;
sub.addEventListener('click', function(e) {
let attrState = subParent.getAttribute('aria-expanded');
if (attrState === 'false') {
subParent.setAttribute('aria-expanded', 'true')
} else if (attrState === 'true') {
subParent.setAttribute('aria-expanded', 'false');
}
console.log('CLICK');
e.stopImmediatePropagation();
});
})
}
function menu_onFocus() {
focusEntry.forEach(sub => {
var subParent = sub.parentElement;
sub.addEventListener('keyup', (e) => {
console.log('TOUCHE');
if (e.keyCode === 27) {
console.log('ECHAP');
subParent.setAttribute('aria-expanded', 'false');
}
e.stopImmediatePropagation();
});
})
}
function menu_onFocusDetection() {
focusDetectionEntry.forEach(sub => {
var subParent = sub.parentElement;
sub.addEventListener('focus', function (e) {
subParent.setAttribute('aria-expanded', 'true');
console.log('FOCUS');
e.stopImmediatePropagation();
});
subParent.addEventListener('focusout', function (e) {
console.log('FOCUS OUT');
//console.log(e.relatedTarget); //target actuel
if (!subParent.contains(e.relatedTarget)) {
subParent.setAttribute('aria-expanded', 'false');
}
e.stopImmediatePropagation();
});
})
}
I tried something like that, but not successfull :
function menu_onFocusDetection() {
focusDetectionEntry.forEach(sub => {
var subParent = sub.parentElement;
// si focus sur le bouton, on modifie sont parent
function test(ev) {
subParent.setAttribute('aria-expanded', 'true');
console.log('FOCUS');
ev.stopImmediatePropagation();
}
// si le focus sort du li
function test2(ev2) {
// console.log(ev2.relatedTarget); //target actuel
console.log('FOCUS OUT');
if (!subParent.contains(ev2.relatedTarget)) {
subParent.setAttribute('aria-expanded', 'false');
}
ev2.stopImmediatePropagation();
}
if (window.innerWidth > 770) {
sub.addEventListener('focus', test);
sub.addEventListener('focusout', test2);
} else {
sub.removeEventListener('focus', test);
sub.removeEventListener('focusout', test2);
}
})
}
Ok, so here it is the answer :
I had to split my function and do the condition in each.
window.addEventListener("DOMContentLoaded", onLoadFunction);
function onLoadFunction(e) {
onResizeFunction(); //trigger resize function immediately
window.addEventListener("resize", onResizeFunction);
}
function onResizeFunction(e) {
menu_onFocusDetection();
}
function initEntries() {
focusDetectionEntry = document.querySelectorAll('.nav-list--focus-detection > li[aria-expanded] > button');
}
function focus(e) {
this.parentElement.setAttribute('aria-expanded', 'true');
e.stopImmediatePropagation();
}
function menu_onFocusDetection() {
focusDetectionEntry.forEach(sub => {
var subParent = sub.parentElement;
if (window.innerWidth > 770) {
sub.addEventListener('focus', focus);
subParent.addEventListener('focusout', focusOut);
} else {
sub.removeEventListener('focus', focus);
subParent.removeEventListener('focusout', focusOut);
}
});
}
Event handlers are executed every time an event occurs, not just the first time. They need to be registered only once.
Move the click and mouseover handlers to standalone function declarations, and register those handlers in the outer block. So basically:
window.addEventListener("load", onLoadFunction);
function onLoadFunction(e) {
onResizeFunction();// trigger resize function immediately
window.addEventListener("resize", onResizeFunction);
}
function onResizeFunction(e) {
if (window.innerWidth > 770) {
//over + click
over();
click();
} else {
//only click
click();
}
}
function click() {
console.log('CLICK');
}
function over() {
console.log('OVER');
}
document.querySelector('.test').addEventListener('click', click);
document.querySelector('.test').addEventListener('mouseover', over);

Cursor pointer moves to first position onclick textarea using CK-Editor

I am using CK-Editor 4. In which I have created Directive. When I click on Textarea my cursor pointer is Move to First position. I want my cursor position should be available when I click in any of the Place inside Textarea. It should not be able to move first or last position until I click on last position.
vpb.directive('ckeInline', function ($timeout, $parse, $rootScope,$) {
return {
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
if (attrs.ckeInlineShowtitle) ngModel = "";
isMobile = $(".ipad, .ipod, .android").length > 0;
var destroy_this_editor = function(id)
{
setTimeout(function () {
try{
CKEDITOR.instances[id].destroy(true);
} catch (ex) {
}
},500)
}
if (!isMobile) {
var create_and_focus = function () {
if (scope.setup.edit_mode || attrs.ckeNonEditMode) {
attrs.$set('contenteditable', true);
var a_id = attrs.ckeInlineId;
var menu_selector = attrs.ckeInlineMenu;
//get editor
//create editor if doesn't exist
var e = CKEDITOR.instances[a_id];
if (!e) {
element.menu = $(menu_selector);
//set up behavior for menu
uif.wire_up_menu(element, scope);
//hide all menu bars
$("nav.text-editor-menu-bar").hide();
//create editor
var config = {
toolbar: "More",
on: {
'blur': function () {
save_editor_content(function () {
destroy_this_editor(a_id);
});
},
'focusout': function () {
save_editor_content(function () {
destroy_this_editor(a_id);
});
},
'focus': function () {
//show the current menu
element.menu.show();
//fix menu width
uif.stretch_menu(element);
},
'instanceReady': function (event,element) {
//----------------I think,Here i want logic to set caret sign or set mouse
//pointer to appropriate place
// event.editor.focus();
// element.focus();
}
}
};
if (attrs.ckeInlineToolbar) {
config.toolbar = attrs.ckeInlineToolbar;
}
var editor = CKEDITOR.inline(a_id, config);
if (attrs.ckeInlineOnInit) {
uif.apply_scope($rootScope, $parse(attrs.ckeInlineOnInit));
}
}
else
{
e.focus();
element.focus();
}
} else
{
attrs.$set('contenteditable', false);
}
}
element.click(function () {
create_and_focus();
});
if (attrs.ckeInlineFocusWatch) {
scope.$watch(function () {
return $parse(attrs.ckeInlineFocusWatch);
}, function () {
if (attrs.ckeInlineFocusCondition == undefined || $parse(attrs.ckeInlineFocusCondition)() == true) {
create_and_focus();
}
})
}
var saving = false;
var save_editor_content = function (cb) {
if (!saving)
{
saving = true;
var a_id = attrs.ckeInlineId;
if (a_id) {
var editor = CKEDITOR.instances[a_id];
if (editor) {
var menu_selector = attrs.ckeInlineMenu;
element.menu.hide();
//attrs.$set('contenteditable', false);
var newValue = editor.getData().replace(/ /, ' ');
if (ngModel.$modelValue != newValue) {
if (attrs.ckeInlineBlurBool) {
$parse(attrs.ckeInlineBlurBool).assign($rootScope, false);
}
ngModel.$setViewValue(newValue);
if (attrs.ckeInlineSave) {
uif.apply_scope(scope, $parse(attrs.ckeInlineSave));
}
$timeout(function () {
saving = false;
if (cb) cb();
}, 1100)
} else
{
saving = false;
$rootScope.setup.blcok_edits = false;
$rootScope.setup.block_all_editors = false;
if (cb) cb();
}
}
}
else
{
saving = false;
}
}
};
} else if (attrs.ckeNonEditMode) {
attrs.$set('contenteditable', true);
element.blur(function () {
ngModel.$setViewValue(element.html().replace(/ /, ' '));
if (attrs.ckeInlineSave) {
uif.apply_scope(scope, $parse(attrs.ckeInlineSave));
}
})
}
}
}
});

Run function once then disallow further calls for 5 seconds

I want to stop a function being fired again for 5 seconds after the last.
This is what I had:
return {
buildUI: function() {
el.nav.on({
mouseenter: function() {
el.logo.addClass('spin');
},
mouseleave: function() {
el.logo.removeClass('spin');
}
});
}
}
On mouseenter, add class to spin the logo. On mouseleave, remove the class. But to stop the logo spinning every mouseenter, I want to add a 5 second ban since the last.
This is what I tried, amongst other attempts:
var flipLogoTimer;
return {
el.nav.on({
mouseenter: function() {
if (!flipLogoTimer) {
el.logo.removeClass('spin').addClass('spin');
}
},
mouseleave: function() {
el.logo.removeClass('spin');
flipLogoTimer = setTimeout(function() {
//
}, 5000);
}
});
}
I tried to add a 5 second timer to the mouseleave event, so the next mouseenter can check if the timer is still running to determine whether or not to run the animation again.
Where am I going wrong and is there a better way? It's a difficult one to search for, as there are so many questions about running a function on a timer.
You can use the flag like
return {
buildUI: function () {
var flag = false;
el.nav.on({
mouseenter: function () {
if (flag) {
return;
}
el.logo.addClass('spin');
},
mouseleave: function () {
if (flag) {
return;
}
flag = true;
el.logo.removeClass('spin');
setTimeout(function () {
flag = false;
}, 5000)
}
});
}
}
You can try something like this by toggling value of flipLogoTimer
var flipLogoTimer=false;
return {
el.nav.on({
mouseenter: function() {
if (!flipLogoTimer) {
el.logo.removeClass('spin').addClass('spin');
}
},
mouseleave: function() {
el.logo.removeClass('spin');
flipLogoTimer=true;
setTimeout(function() {
flipLogoTimer=false;
}, 5000);
}
});
}
You can use timestamp. Idea: you fix last time when you added/removed class, and compare it with current date.
// 5000 - equal to 5 seconds
function checkTimestamp(a, b){
return Math.abs(a - b) < 5000;
}
return {
buildUI: function () {
var lastTimeStamp = null;
el.nav.on({
mouseenter: function () {
if(lastTimeStamp && checkTimestamp(lastTimeStamp, Date.now())
return false;
el.logo.addClass('spin');
lastTimeStamp = Date.now();
},
mouseleave: function () {
if(lastTimeStamp && checkTimestamp(lastTimeStamp, Date.now())
return false;
el.logo.removeClass('spin');
lastTimeStamp = Date.now();
}
});
}
}

I was trying to make a news ticker. But there's an error when mouse leaves after hover

After Mouse Leave the ticker starts to move at a very high speed. Don't know what's the error.
Javascript:
$('#tick2').html($('#tick').html());
var temp=0,intervalId=0;
$('#tick li').each(function() {
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick').css({'width':temp+40, 'margin-left':'20px'});
temp=0;
$('#tick2 li').each(function(){
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick2').css({'width':temp+40,'margin-left':temp+40});
function abc(a,b) {
$('#outer').mouseenter(function() { window.clearInterval(intervalId);intervalId=0; });
$('#outer').mouseleave(function() { start(); })
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
start();
You can check the working demo here : http://jsfiddle.net/mstoic/juJK2/
Well, you nearly blew up my browser! Can you try this instead:
function abc(a,b) {
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
$(function(){
$('#outer').mouseenter(function() { window.clearInterval(intervalId); });
$('#outer').mouseleave(function() { start(); })
start();
});
Working fiddle: http://jsfiddle.net/juJK2/1/
You should only bind your event handlers once, not every time you enter abc();

Manually calling PDFJS functions. What func to call after PDFView.open to render

CanĀ“t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call! Thanks
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...

Categories

Resources