Smarter code that avoid repetition to control multiple players in one page - javascript

for a one-page portfolio, I have some repetition code for each button that control some video players populated by CMS.
I’ll have 15 to 20 players to control with each one is own button on the page to launch it , and return button to stop (1 on each section). I use Webflow which limit the number of characters for the code.
I would love to find the shorter/smarter way to write this for each player without 20 repetition in the code.
///////// for Player 0 //
// Play on click .titre
on('#titre-2', 'click', () => {
players[0].play();
});
// Stop and back to 0 at end
players[0].on('ended', function(event) {
players[0].pause();
players[0].currentTime = 0;
////////// for Player 1 //
// play on click .titre
on('#titre-3', 'click', () => {
players[1].play();
});
// stop at end
players[1].on('ended', function(event) {
players[1].pause();
players[1].currentTime = 0;
});
/////// for player 3 ////
...
... and so on for 15 to 20 players, until last player
(number of players is subject to change when updating the portfolio with CMS)
EDIT : here is the full code from the beginning, with the part of the code for each player at the end, that need to be improved :
<script src="https://cdn.plyr.io/3.5.6/plyr.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const controls = [
'play-large','restart','play','progress',
'current-time','mute','volume','fullscreen'
];
//init PLAYERS
const players = Array.from(document.querySelectorAll('.player_js')).map(p => new Plyr(p,{ controls }));
// Expose player so it can be used from the console
window.players = players;
// Bind event listener
function on(selector, type, callback) {
document.querySelector(selector).addEventListener(type, callback, false);
}
///////// for Player 0 //
// Play on click .titre
on('#titre-2', 'click', () => {
players[0].play();
});
// Stop and back to 0 at end
players[0].on('ended', function(event) {
players[0].pause();
players[0].currentTime = 0;
////////// for Player 1 //
// play on click .titre
on('#titre-3', 'click', () => {
players[1].play();
});
// stop at end
players[1].on('ended', function(event) {
players[1].pause();
players[1].currentTime = 0;
});
/////// for player 3 ////
/// AND SO ON ...
});

You can loop the code :
for(let x = 0 ; x < 20 ; x ++){
// Play on click .titre
on('#titre-' + (x + 2), 'click', () => {
players[x].play();
});
// Stop and back to 0 at end
players[x].on('ended', function(event) {
players[x].pause();
players[x].currentTime = 0;
}
But the best solution is create a class of players

Related

Concatenate function

The idea behind this to animate section with mousewheel - keyboard and swipe on enter and on exit. Each section has different animation.
Everything is wrapp inside a global variable. Here is a bigger sample
var siteGlobal = (function(){
init();
var init = function(){
bindEvents();
}
// then i got my function to bind events
var bindEvents = function(){
$(document).on('mousewheel', mouseNav());
$(document).on('keyup', mouseNav());
}
// then i got my function here for capture the event
var mouseNav = function(){
// the code here for capturing direction or keyboard
// and then check next section
}
var nextSection = function(){
// Here we check if there is prev() or next() section
// if there is do the change on the section
}
var switchSection = function(nextsection){
// Get the current section and remove active class
// get the next section - add active class
// get the name of the function with data-name attribute
// trow the animation
var funcEnter = window['section'+ Name + 'Enter'];
}
// Let's pretend section is call Intro
var sectionIntroEnter = function(){
// animation code here
}
var sectionIntroExit = function(){
// animation code here
}
}();
So far so good until calling funcEnter() and nothing happen
I still stuck to call those function...and sorry guys i'm really not a javascript programmer , i'm on learning process and this way it make it easy for me to read so i would love continue using this way of "coding"...Do someone has a clue ? Thanks
Your concatenation is right but it'd be better if you didn't create global functions to do this. Instead, place them inside of your own object and access the functions through there.
var sectionFuncs = {
A: {
enter: function() {
console.log('Entering A');
},
exit: function() {
console.log('Exiting A');
}
},
B: {
enter: function() {
console.log('Entering B');
},
exit: function() {
console.log('Exiting B');
}
}
};
function onClick() {
var section = this.getAttribute('data-section');
var functions = sectionFuncs[section];
functions.enter();
console.log('In between...');
functions.exit();
}
var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', onClick);
}
<button data-section="A">A</button>
<button data-section="B">B</button>
You could have an object that holds these functions, keyed by the name:
var enterExitFns = {
intro: {
enter: function () {
// animation code for intro enter
},
exit: function () {
// animation code for intro exit
}
},
details: {
enter: function () {
// animation code for details enter
},
exit: function () {
// animation code for details exit
}
}
};
var name = activeSection.attr('data-name');
enterExitFns[name].enter();

How to make an audio file wait for the end of another one in order to start them together

I'm trying to build a basic sampler. I have 4 different audio files (1 guitar, 1 drum, 1 piano and 1 bass). The sound kit buttons programmed the way I want, but I cannot get the loops to work the way I want.
What i want to do is this :
if the user clicks on a button it launches the sample
if the user clicks again on the same button it stops the sample
and if the user clicks on another sample it waits for the end of the first sample and then start together
For now i manage to do the first and the second steps but i can't figure how to do the third one.
I tried to use Event Listener to know when a loop ends but i've never managed to make it work.
So my question is : is there an easy to do this third step ?
If you could give me a bit more detail when explaining, that would be great. Thanks!
Here what's my js look like so far :
$(document).ready(function() {
var basse = {
padOne: new Audio('basse2.mp3'),
};
var drum = {
padOne: new Audio('m1_drum1_85.mp3'),
};
var guitar = {
padOne: new Audio('m1_guitare1_85.mp3'),
};
var piano = {
padOne: new Audio('m1_piano_85.mp3'),
};
$('.pad-1').mousedown(function() {
if (basse.padOne.paused) {
basse.padOne.load()
basse.padOne.loop = true;
basse.padOne.play();
} else {
basse.padOne.pause();
basse.padOne.currentTime = 0
}
});
$('.pad-5').mousedown(function() {
if (drum.padOne.paused) {
drum.padOne.load()
drum.padOne.loop = true;
drum.padOne.play();
} else {
drum.padOne.pause();
drum.padOne.currentTime = 0
}
});
$('.pad-9').mousedown(function() {
if (guitar.padOne.paused) {
guitar.padOne.load()
guitar.padOne.loop = true ;
guitar.padOne.play();
} else {
guitar.padOne.pause();
guitar.padOne.currentTime = 0
}
});
$('.pad-13').mousedown(function() {
if (piano.padOne.paused) {
piano.padOne.load()
piano.padOne.loop = true ;
guitar.padOne.play();
} else {
piano.padOne.pause();
piano.padOne.currentTime = 0
}
});
});

How to Monitor user idle in an applet inside a html using java script [duplicate]

Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
I define idle time as a period of user inactivity or without any CPU usage
Here is a simple script using jQuery that handles mousemove and keypress events.
If the time expires, the page reloads.
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
// Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
// Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
window.location.reload();
}
}
</script>
With vanilla JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeydown = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.html'
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
// 1000 milliseconds = 1 second
}
};
And initialise the function where you need it (for example: onPageLoad).
window.onload = function() {
inactivityTime();
}
You can add more DOM events if you need to. Most used are:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onkeydown = resetTimer; // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments
Or register desired events using an array
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp
Remember to use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in JavaScript?
Code Updated with #frank-conijn and #daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. In window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch the event during the capture phase instead of the bubble phase.
Improving on Equiman's (original) answer:
function idleLogout() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.ontouchmove = resetTimer; // required by some devices
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeydown = resetTimer;
window.addEventListener('scroll', resetTimer, true); // improved; see comments
function yourFunction() {
// your function for too long inactivity goes here
// e.g. window.location.href = 'logout.php';
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(yourFunction, 10000); // time is in milliseconds
}
}
idleLogout();
Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.
It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.
I have created a small library that does this:
https://github.com/shawnmclean/Idle.js
Description:
Tiny JavaScript library to report activity of user in the browser
(away, idle, not looking at webpage, in a different tab, etc). that is independent of any
other JavaScript libraries such as jQuery.
Visual Studio users can get it from NuGet by:
Install-Package Idle.js
Here is a rough jQuery implementation of tvanfosson's idea:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})
Similar to Peter J's solution (with a jQuery custom event)...
// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
// Start your prefetch, etc. here...
});
$(window).on('idle:stop', function() {
// Stop your prefetch, etc. here...
});
File jquery-idle-detect.js
(function($, $w) {
// Expose configuration option
// Idle is triggered when no events for 2 seconds
$.idleTimeout = 2000;
// Currently in idle state
var idle = false;
// Handle to idle timer for detection
var idleTimer = null;
// Start the idle timer and bind events on load (not DOM-ready)
$w.on('load', function() {
startIdleTimer();
$w.on('focus resize mousemove keyup', startIdleTimer)
.on('blur', idleStart) // Force idle when in a different tab/window
;
]);
function startIdleTimer() {
clearTimeout(idleTimer); // Clear prior timer
if (idle) $w.trigger('idle:stop'); // If idle, send stop event
idle = false; // Not idle
var timeout = ~~$.idleTimeout; // Option to integer
if (timeout <= 100)
timeout = 100; // Minimum 100 ms
if (timeout > 300000)
timeout = 300000; // Maximum 5 minutes
idleTimer = setTimeout(idleStart, timeout); // New timer
}
function idleStart() {
if (!idle)
$w.trigger('idle:start');
idle = true;
}
}(window.jQuery, window.jQuery(window)))
You can do it more elegantly with Underscore.js and jQuery:
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce
My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.
(function () {
var minutes = true; // change to false if you'd rather use seconds
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 3; // 3 minutes in this example
var idleCounter = 0;
document.onmousemove = document.onkeypress = function () {
idleCounter = 0;
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
window.location.reload(); // or whatever you want to do
}
}, interval);
}());
As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.
This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.
All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
document.addEventListener("touchstart", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
document.removeEventListener("touchstart", onActivity);
setTimeout(startTimer, 1000);
}
}
http://jsfiddle.net/9exz43v2/
I had the same issue and I found a quite good solution.
I used jquery.idle and I only needed to do:
$(document).idle({
onIdle: function(){
alert('You did nothing for 5 seconds');
},
idle: 5000
})
See JsFiddle demo.
(Just for information: see this for back-end event tracking Leads browserload)
If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.
You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.
I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:
const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();
It does not depend on jQuery, though you might need to run it through Babel to support older browsers.
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096
(Partially inspired by the good core logic of Equiman's answer.)
sessionExpiration.js
sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:
sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
Affects all tabs of the browser, not just one.
Written in pure JavaScript, with no dependencies. Fully client side.
(If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
Now the user will be logged out automatically if all tabs have been inactive for the given duration.
Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.
This is an example of what it looks like in action, if you don't change the CSS.
Try this code. It works perfectly.
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "SessionExpired.aspx";
}
}
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$('body').mousemove(function (e) {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
$('body').keypress(function (e) {
//alert("keypressed" + idleTime);
idleTime = 0;
});
$('body').click(function() {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 10) { // 10 minutes
window.location.assign("http://www.google.com");
}
}
</script>
I think this jQuery code is perfect one, though copied and modified from above answers!!
Do not forgot to include the jQuery library in your file!
Pure JavaScript with a properly set reset time and bindings via addEventListener:
(function() {
var t,
timeout = 5000;
function resetTimer() {
console.log("reset: " + new Date().toLocaleString());
if (t) {
window.clearTimeout(t);
}
t = window.setTimeout(logout, timeout);
}
function logout() {
console.log("done: " + new Date().toLocaleString());
}
resetTimer();
//And bind the events to call `resetTimer()`
["click", "mousemove", "keypress"].forEach(function(name) {
console.log(name);
document.addEventListener(name, resetTimer);
});
}());
The problem with all these solutions, although correct, is they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for ColdFusion developers.
The time set by the above solution needs to sync with the server-side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users.
For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed.
I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part.
In this way my client side and server-side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session and JavaScript timer are reset. Simple and elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.
You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}
I wrote a simple jQuery plugin that will do what you are looking for.
https://github.com/afklondon/jquery.inactivity
$(document).inactivity( {
interval: 1000, // the timeout until the inactivity event fire [default: 3000]
mouse: true, // listen for mouse inactivity [default: true]
keyboard: false, // listen for keyboard inactivity [default: true]
touch: false, // listen for touch inactivity [default: true]
customEvents: "customEventName", // listen for custom events [default: ""]
triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});
The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.
I have tested this code working file:
var timeout = null;
var timee = '4000'; // default time for session time out.
$(document).bind('click keyup mousemove', function(event) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
console.log('Document Idle since '+timee+' ms');
alert("idle window");
}, timee);
});
Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not?
If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.
Here is the best solution I have found:
Fire Event When User is Idle
Here is the JavaScript:
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
$("body").append("<p>Welcome Back.</p>");
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
I use this approach, since you don't need to constantly reset the time when an event fires. Instead, we just record the time, and this generates the idle start point.
function idle(WAIT_FOR_MINS, cb_isIdle) {
var self = this,
idle,
ms = (WAIT_FOR_MINS || 1) * 60000,
lastDigest = new Date(),
watch;
//document.onmousemove = digest;
document.onkeypress = digest;
document.onclick = digest;
function digest() {
lastDigest = new Date();
}
// 1000 milisec = 1 sec
watch = setInterval(function() {
if (new Date() - lastDigest > ms && cb_isIdel) {
clearInterval(watch);
cb_isIdle();
}
}, 1000*60);
},
Based on the inputs provided by equiman:
class _Scheduler {
timeoutIDs;
constructor() {
this.timeoutIDs = new Map();
}
addCallback = (callback, timeLapseMS, autoRemove) => {
if (!this.timeoutIDs.has(timeLapseMS + callback)) {
let timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
}
if (autoRemove !== false) {
setTimeout(
this.removeIdleTimeCallback, // Remove
10000 + timeLapseMS, // 10 secs after
callback, // the callback
timeLapseMS, // is invoked.
);
}
};
removeCallback = (callback, timeLapseMS) => {
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
if (timeoutID) {
clearTimeout(timeoutID);
this.timeoutIDs.delete(timeLapseMS + callback);
}
};
}
class _IdleTimeScheduler extends _Scheduler {
events = [
'load',
'mousedown',
'mousemove',
'keydown',
'keyup',
'input',
'scroll',
'touchstart',
'touchend',
'touchcancel',
'touchmove',
];
callbacks;
constructor() {
super();
this.events.forEach(name => {
document.addEventListener(name, this.resetTimer, true);
});
this.callbacks = new Map();
}
addIdleTimeCallback = (callback, timeLapseMS) => {
this.addCallback(callback, timeLapseMS, false);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (!callbacksArr) {
this.callbacks.set(timeLapseMS, [callback]);
} else {
if (!callbacksArr.includes(callback)) {
callbacksArr.push(callback);
}
}
};
removeIdleTimeCallback = (callback, timeLapseMS) => {
this.removeCallback(callback, timeLapseMS);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (callbacksArr) {
let index = callbacksArr.indexOf(callback);
if (index !== -1) {
callbacksArr.splice(index, 1);
}
}
};
resetTimer = () => {
for (let [timeLapseMS, callbacksArr] of this.callbacks) {
callbacksArr.forEach(callback => {
// Clear the previous IDs
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
clearTimeout(timeoutID);
// Create new timeout IDs.
timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
});
}
};
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();
As simple as it can get, detect when the mouse moves only:
var idle = false;
document.querySelector('body').addEventListener('mousemove', function(e) {
if(idle!=false)
idle = false;
});
var idleI = setInterval(function()
{
if(idle == 'inactive')
{
return;
}
if(idle == true)
{
idleFunction();
idle = 'inactive';
return;
}
idle = true;
}, 30000); // half the expected time. Idle will trigger after 60 s in this case.
function idleFuntion()
{
console.log('user is idle');
}
Here is an AngularJS service for accomplishing in Angular.
/* Tracks now long a user has been idle. secondsIdle can be polled
at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
var self = {
secondsIdle: 0,
init: function(){
$(document).mousemove(function (e) {
self.secondsIdle = 0;
});
$(document).keypress(function (e) {
self.secondsIdle = 0;
});
$interval(function(){
self.secondsIdle += 1;
}, 1000)
}
}
return self;
}]);
Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.
myApp.run(['idleChecker',function(idleChecker){
idleChecker.init();
}]);
Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.
You can see an elegant usage of this API in the Quicklink repo.
const requestIdleCallback = window.requestIdleCallback ||
function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
The meaning of the code above is: if the browser supports requestIdleCallback (check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1) as fallback, which should queue the function to be called at the end of the event loop.
Then you can use it like this:
requestIdleCallback(() => {...}, {
timeout: 2000
});
The second parameter is optional, you might want to set a timeout if you want to make sure the function is executed.
You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WoW and just isn't looking at your page at this time.
Generally, I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality, you do something with an ActiveX control in Windows, but it's ugly at best.
Debounce is actually a great idea! Here is a version for jQuery-free projects:
const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);
function createDerivedLogout (sessionTimeoutInMinutes) {
return _.debounce( () => {
window.location = this.logoutUrl;
}, sessionTimeoutInMinutes * 60 * 1000 )
}

Hide background-image inline styling from source code

I needed to create a simple memory game for a course I'm attending and I came up with this:
Simple memory game
$(document).ready(function(){
// Set initial time to 0
var currentTime = 0;
// Set initial score to 0
var score = 0;
// Set initial attempt to 0
var attempts = 0;
// Placeholder
var timeHolder;
// Start the game when clicking the button #start
$('#start').on('click', init);
// Check if user hasn't clicked #start button yet
$('.board_cell').on('click.initialCheck', checkInitial);
function init() {
// Shuffle elements at beginning
shuffle();
// Handle click event and check if elements match
$('.board_cell').on('click', checkAccuracy).off('click.initialCheck');
$('#start').off('click', init);
$('#reset').on('click', reset);
// stop timer
clearInterval(timeHolder)
// Timer function will be called every 100ms
timeHolder = window.setInterval(timer, 100);
}
/*
* Main function to handle click events and do actions
* #checkAccuracy
*/
function checkAccuracy() {
var self = $(this),
allElements = $('.board_cell'),
// Url of background-image
bgUrl = self.children('.back').css('background-image'),
// Get relevant part (the image name) from the url
elementType = bgUrl.slice(bgUrl.lastIndexOf('/') + 1, bgUrl.lastIndexOf('.'));
// Flip the clicked element
self.addClass('flipped ' + elementType);
// Check if clicked element is already visible
if (self.hasClass('success')) {
showMessage('Das ist schon aufgedeckt ;)');
// Abort function by returning false
return false;
}
if($('.flipped').length >= 2) {
// Prevent clicking on other elements when 2 elements are already visible
allElements.off('click');
// Increase attempts
attempts++;
setAttempts();
}
if($('.'+elementType).length == 2) {
// If the same are visible
score++;
setScore();
showMessage(['That was a right one!!!', 'Now you got it!', 'Terrific!']);
toggleClasses('success', function(){
// Callback when toggleClasses has finsihed
if($('.success').length == allElements.length){
// If alle elements are visible
showMessage('Everything exposed, congrats!');
$('#overlay').fadeIn();
// Kill interval to prevent further increasing
clearInterval(timeHolder);
}
});
} else {
// If they are not the same
if($('.flipped').length == 2) {
toggleClasses();
showMessage(['Uhh that was wrong...', 'Are you drunk?', 'Try it again...', 'You better stop playing!',
'Seems like you need to train much more...', 'Annoying?', 'C\'mon!']);
}
}
}
/*
* Function to reset the game
*/
function reset() {
// turn elements and prevent clicking
$('.board_cell').removeClass('success flipped').off('click');
// hide overlay if visible
if($('#overlay').is(':visible')) {
$('#overlay').fadeOut();
}
// stop timer
clearInterval(timeHolder)
// set time to 0
currentTime = 0;
// set attempts to 0
attempts = 0;
setAttempts();
// set score to 0
score = 0;
setScore();
// hide message
showMessage('');
// set visible time to 0
$('#time span').text(currentTime);
// Check if user has clicked #start button
$('.board_cell').on('click.initialCheck', checkInitial);
$('#start').on('click', init);
}
/*
* Function to show a message
*/
function showMessage(msg) {
if(typeof msg == 'object') {
var randomNumber = Math.floor((Math.random()*msg.length)+1);
msg = msg[randomNumber-1];
}
$('#message span').html(msg);
}
/*
* Function to toggleClasses on clickable elements
*/
function toggleClasses(extraClass, callback) {
setTimeout(function(){
$('.flipped').removeClass().addClass('board_cell '+extraClass);
$('.board_cell').on('click', checkAccuracy);
if(typeof callback != 'undefined') {
callback();
}
}, 1000);
}
/*
* Function to increase score
*/
function setScore() {
$('#score span').text(score);
}
/*
* Function to increase attempts
*/
function setAttempts() {
$('#attempts span').text(attempts);
}
/*
* Function for timer
*/
function timer() {
currentTime = currentTime + 1;
$('#time span').text(currentTime/10);
}
/*
* Function for showing message when user hasn't clicked #start button yet
*/
function checkInitial() {
showMessage('You need to press the "Start Game" button to beginn');
}
/*
* Function for shuffling elements
*/
function shuffle() {
var elementsArray = [];
$('.back').each(function(index){
elementsArray.push($(this).css('background-image'))
});
elementsArray.sort(function() {return 0.5 - Math.random()})
$('.back').each(function(index){
$(this).css('background-image', elementsArray[index]);
});
}
});
The hidden images are added through inline styling with background-image and are shuffled on each start/reset but that doesn't prevent a user to cheat during the game (looking at the source code tells the solution immediately).
I'd like to know if there is a way to hide the background-image value in the source code?
I tried some base64 encryption but as the browser interprets this immediately it doesn't serve at all. Another idea I had was to encrypt the background-image with php, display a random output (which was saved in a database for instance) in the markup and communicate through ajax requests with the php file on each click event. I'm not sure if this works, but anyway it seems like a circuitous way of handling it..
Any suggestion on how to solve this in safe and efficient way?
A safe (and overkill) solution would be to do this entirely serverside. Start a new game by generating a random session id and shuffling the squares. Then, your clientside JS requests the square images through AJAX via some sort of API:
GET /<session_id>/square/<x>/<y>
Once you rate limit the requests serverside to prevent a user from downloading all of the images at once, your game is safe.

NEED HELP. Author has abandoned to fix this jQuery plugin!

I am trying to implemented this jQuery news ticker style plugin from http://www.makemineatriple.com/2007/10/bbcnewsticker
Like mentioned in the comments (around May) there is a bug and the author lost its will to give a bug fix.
The bug is:
In Mac browsers (Firefox, Opera and Safari, all OSX) - links (a href) don’t ‘work’ until each list item has finished scrolling/revealing. Basically after this plugin has loaded, all the a href stops working.
Here is the code for the plugin (http://plugins.jquery.com/project/BBCnewsTicker):
/*
News ticker plugin (BBC news style)
Bryan Gullan,2007-2010
version 2.2
updated 2010-04-04
Documentation at http://www.makemineatriple.com/news-ticker-documentation/
Demo at http://www.makemineatriple.com/jquery/?newsTicker
Use and distrubute freely with this header intact.
*/
(function($) {
var name='newsTicker';
function runTicker(settings) {
tickerData = $(settings.newsList).data('newsTicker');
if(tickerData.currentItem > tickerData.newsItemCounter){
// if we've looped to beyond the last item in the list, start over
tickerData.currentItem = 0;
}
else if (tickerData.currentItem < 0) {
// if we've looped back before the first item, move to the last one
tickerData.currentItem = tickerData.newsItemCounter;
}
if(tickerData.currentPosition == 0) {
if(tickerData.newsLinks[tickerData.currentItem].length > 0) {
$(tickerData.newsList).empty().append('<li></li>');
}
else {
$(tickerData.newsList).empty().append('<li></li>');
}
}
//only start the ticker itself if it's defined as animating: otherwise it's paused or under manual advance
if (tickerData.animating) {
if( tickerData.currentPosition % 2 == 0) {
var placeHolder = tickerData.placeHolder1;
}
else {
var placeHolder = tickerData.placeHolder2;
}
if( tickerData.currentPosition < tickerData.newsItems[tickerData.currentItem].length) {
// we haven't completed ticking out the current item
var tickerText = tickerData.newsItems[tickerData.currentItem].substring(0,tickerData.currentPosition);
if(tickerData.newsLinks[tickerData.currentItem].length > 0) {
$(tickerData.newsList + ' li a').text(tickerText + placeHolder);
}
else {
$(tickerData.newsList + ' li').text(tickerText + placeHolder);
}
tickerData.currentPosition ++;
setTimeout(function(){runTicker(settings); settings = null;},tickerData.tickerRate);
}
else {
// we're on the last letter of the current item
if(tickerData.newsLinks[tickerData.currentItem].length > 0) {
$(tickerData.newsList + ' li a').text(tickerData.newsItems[tickerData.currentItem]);
}
else {
$(tickerData.newsList + ' li').text(tickerData.newsItems[tickerData.currentItem]);
}
setTimeout(function(){
if (tickerData.animating) {
tickerData.currentPosition = 0;
tickerData.currentItem ++;
runTicker(settings); settings = null;
}
},tickerData.loopDelay);
}
}
else {// settings.animating == false
// display the full text of the current item
var tickerText = tickerData.newsItems[tickerData.currentItem];
if(tickerData.newsLinks[tickerData.currentItem].length > 0) {
$(tickerData.newsList + ' li a').text(tickerText);
}
else {
$(tickerData.newsList + ' li').text(tickerText);
}
}
}
// Core plugin setup and config
jQuery.fn[name] = function(options) {
// Add or overwrite options onto defaults
var settings = jQuery.extend({}, jQuery.fn.newsTicker.defaults, options);
var newsItems = new Array();
var newsLinks = new Array();
var newsItemCounter = 0;
// Hide the static list items
$(settings.newsList + ' li').hide();
// Store the items and links in arrays for output
$(settings.newsList + ' li').each(function(){
if($(this).children('a').length) {
newsItems[newsItemCounter] = $(this).children('a').text();
newsLinks[newsItemCounter] = $(this).children('a').attr('href');
}
else {
newsItems[newsItemCounter] = $(this).text();
newsLinks[newsItemCounter] = '';
}
newsItemCounter ++;
});
var tickerElement = $(settings.newsList); // for quick reference below
tickerElement.data(name, {
newsList: settings.newsList,
tickerRate: settings.tickerRate,
startDelay: settings.startDelay,
loopDelay: settings.loopDelay,
placeHolder1: settings.placeHolder1,
placeHolder2: settings.placeHolder2,
controls: settings.controls,
ownControls: settings.ownControls,
stopOnHover: settings.stopOnHover,
newsItems: newsItems,
newsLinks: newsLinks,
newsItemCounter: newsItemCounter - 1, // -1 because we've incremented even after the last item (above)
currentItem: 0,
currentPosition: 0,
firstRun:1
})
.bind({
stop: function(event) {
// show remainder of the current item immediately
tickerData = tickerElement.data(name);
if (tickerData.animating) { // only stop if not already stopped
tickerData.animating = false;
}
},
play: function(event) {
// show 1st item with startdelay
tickerData = tickerElement.data(name);
if (!tickerData.animating) { // if already animating, don't start animating again
tickerData.animating = true;
setTimeout(function(){runTicker(tickerData); tickerData = null;},tickerData.startDelay);
}
},
resume: function(event) {
// start from next item, with no delay
tickerData = tickerElement.data(name);
if (!tickerData.animating) { // if already animating, don't start animating again
tickerData.animating = true;
// set the character position as 0 to ensure on resume we start at the right point
tickerData.currentPosition = 0;
tickerData.currentItem ++;
runTicker(tickerData); // no delay when resuming.
}
},
next: function(event) {
// show whole of next item
tickerData = tickerElement.data(name);
// stop (which sets as non-animating), and call runticker
$(tickerData.newsList).trigger("stop");
// set the character position as 0 to ensure on resume we start at the right point
tickerData.currentPosition = 0;
tickerData.currentItem ++;
runTicker(tickerData);
},
previous: function(event) {
// show whole of previous item
tickerData = tickerElement.data(name);
// stop (which sets as non-animating), and call runticker
$(tickerData.newsList).trigger("stop");
// set the character position as 0 to ensure on resume we start at the right point
tickerData.currentPosition = 0;
tickerData.currentItem --;
runTicker(tickerData);
}
});
if (settings.stopOnHover) {
tickerElement.bind({
mouseover: function(event) {
tickerData = tickerElement.data(name);
if (tickerData.animating) { // stop if not already stopped
$(tickerData.newsList).trigger("stop");
if (tickerData.controls) { // ensure that the ticker can be resumed if controls are enabled
$('.stop').hide();
$('.resume').show();
}
}
}
});
}
tickerData = tickerElement.data(name);
// set up control buttons if the option is on
if (tickerData.controls || tickerData.ownControls) {
if (!tickerData.ownControls) {
$('<ul class="ticker-controls"><li class="play">Play</li><li class="resume">Resume</li><li class="stop">Stop</li><li class="previous">Previous</li><li class="next">Next</li></ul>').insertAfter($(tickerData.newsList));
}
$('.play').hide();
$('.resume').hide();
$('.play').click(function(event){
$(tickerData.newsList).trigger("play");
$('.play').hide();
$('.resume').hide();
$('.stop').show();
event.preventDefault();
});
$('.resume').click(function(event){
$(tickerData.newsList).trigger("resume");
$('.play').hide();
$('.resume').hide();
$('.stop').show();
event.preventDefault();
});
$('.stop').click(function(event){
$(tickerData.newsList).trigger("stop");
$('.stop').hide();
$('.resume').show();
event.preventDefault();
});
$('.previous').click(function(event){
$(tickerData.newsList).trigger("previous");
$('.stop').hide();
$('.resume').show();
event.preventDefault();
});
$('.next').click(function(event){
$(tickerData.newsList).trigger("next");
$('.stop').hide();
$('.resume').show();
event.preventDefault();
});
};
// tell it to play
$(tickerData.newsList).trigger("play");
};
// News ticker defaults
jQuery.fn[name].defaults = {
newsList: "#news",
tickerRate: 80,
startDelay: 100,
loopDelay: 3000,
placeHolder1: " |",
placeHolder2: "_",
controls: true,
ownControls: false,
stopOnHover: true
}
})(jQuery);
Any solutions? I am not a programmer so if someone could point out where to patch it greatly appreciated!
UPDATE: it seems only the links with ? mark becomes disabled.
Example: http://url.com/blog/index.html?page=2
I just happened to come across this post. I do still support the ticker, and there have been a few releases since last July.
The way to mitigate this issue was that there's now a "stop on hover" option, which pauses the ticker and completes (immediately) the display of an item when the user hovers over it (including of course being about to click it).
If this is still of relevance to you, if you still have issues with the latest version it'd be worth reading through the thread of comments; please do get in touch if you've still a problem (if one of the comments was yours and I missed it, then sorry!). The "official" way is to post a bug report on the jQuery plugins site, which fully tracks any reported issues, but I do try to respond to anyone who requests support via the blog.
If there are any elements with the ID of news in your document, there might be a collision happening... Might this be the case? I'd search your html document for any occurrences of id="news" and correct them, seeing as though passing the proper parameters into the plugin might require a bit of extra research.

Categories

Resources