An issue with CSS animations and JS classList.add - javascript

I'm writing a private 'framework' of sorts in order to have some basic effects without the need of jQuery.
I've just written some code for fade-ins/outs, and basically what I do is add/remove classes, and check for animation support.
Here's the JavaScript part (please, check mainly the fadeIn, fadeOut properties):
var effs = {
checkSupport: (function() {
var init = true;
var supports = false;
return function(el) {
if (init) {
var animationstring = 'animation',
keyframeprefix = '',
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
pfx = '';
if (el.style.animationName !== undefined) {
supports = true;
}
if (supports === false) {
for (var i = 0; i < domPrefixes.length; i++) {
if (el.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
pfx = domPrefixes[i];
animationstring = pfx + 'Animation';
keyframeprefix = '-' + pfx.toLowerCase() + '-';
supports = true;
break;
}
}
}
init = false;
}
return supports;
};
}()),
fadeOut: function(el) {
el.style.opacity = 1;
if (this.checkSupport(el)) {
el.classList.remove("fadeIn", "fadeOut");
//Here comes the annoying timeout!
setTimeout(function() {
el.classList.add("fadeOut");
}, 25);
} else {
el.style.opacity = 0;
}
},
fadeIn: function(el) {
el.style.opacity = 0;
if (this.checkSupport(el)) {
el.classList.remove("fadeIn", "fadeOut");
setTimeout(function() {
el.classList.add("fadeIn");
}, 25);
} else {
el.style.opacity = 1;
}
}
};
As you can see, I have had to delay the addition of the animation class, because without that timeout, the animation doesn't show the second time around in Chrome(and other Webkit browsers), when it is called on the same element. It does work in Firefox without the timeout, though.
I also tested this in Midori, and since it's also a Webkit browser, it needs the timeout as well, but with the added annoyance of the delay being even longer than 25ms, for some reason.
Why is this? Is there any other way around that you can think of? I know these methods aren't very compatible with a lot of browsers, but I don't mind the animations not showing in some of them. Thank you.

Related

audio.play() works in Chrome but not Safari

I know there are questions similar to this on this site that have been answered, but I haven't found any that fix this issue which is why I'm making a post.
Here is what I have tried:
Listening for events "canplay", "loadedmetadata", "canplaythrough"
Doing audio.load() on initialization
Setting audio.preload to "auto"
Testing on Chrome (it works perfectly in this browser!)
Appending the audio element to document.body on initialization
When I try to play() without the eventListener (which also doesn't work), the console says: Unhandled Promise Rejection: NotSupportedError: The operation is not supported.
Am I missing something?
The code:
var AUDIO = {
create: function(name, file, type) {
AUDIO.library[name] = {};
AUDIO.library[name].type = type;
AUDIO.library[name].audio = new Audio();
AUDIO.library[name].audio.preload = "auto";
if (type=="music") {
AUDIO.library[name].audio.loop = true;
}
AUDIO.library[name].audio.src = file;
AUDIO.library[name].audio.load();
},
play: function(name, fadeout_playing) {
if (fadeout_playing) {
for (let i=0; i<AUDIO.playing.length; i++) {
let n = AUDIO.playing[i];
AUDIO.fadeout(n);
}
}
let a = AUDIO.library[name].audio;
a.currentTime = 0;
a.addEventListener("canplaythrough", function() {
console.log("you are listening to: "+ name);
AUDIO.playing.push(name);
a.play();
}, false);
},
fadeout: function(name) {
var sound = AUDIO.library[name].audio;
var fade = setInterval(function() {
if (sound.volume >= 0.1) {
sound.volume -= 0.1;
sound.volume = sound.volume.toFixed(1);
}
if (sound.volume <= 0) {
sound.volume = 0;
let index = AUDIO.playing.indexOf(name);
AUDIO.playing.splice(index, 1);
clearInterval(fade);
}
}, 200);
},
library: {},
playing: [],
};
AUDIO.create("act1", "music/chillelectric.mp3", "music");
//this runs when i click a button
function setup() {
...
AUDIO.play("act1");
}
Thanks in advance.

Allow chaining in jQuery plugin

it's been a long day and I can't seem to figure out why one of my custom jQuery plugins won't chain.
What i'm trying to do is write a line of characters out one at a time in an element then when done remove the text then write the next line
The plugin:
(function($) {
$.fn.writeDialogue = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this,
write = setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
} else {
clearInterval(write);
return this;
}
}, 100);
};
})(jQuery);
Pretty much i'm trying to chain it in this way:
$('#element').writeDialogue(textLine1).empty().writeDialogue(textLine2);
Can't get it to work, any ideas?
This is because your code is async. so you have to move return this:
(function($) {
$.fn.writeDialogue = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this,
write = setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
} else {
clearInterval(write);
}
}, 100);
return this; // THERE
};
})(jQuery);

Extend Zepto.js with a jQuery method? scrollTop()

I'm using Zepto.js on a current project. Zepto doesn't support the scrollTop() method that jQuery has in it.
Is it possible to kind of extend Zepto to work with scrollTop() too?
Update: All I want is to create my own small and simple "animated scroll" function like I have used before with jQuery. See the working example here. However I have no idea how to make the same function work without the scrollTop() function available in Zepto.js.
scrollTop isn't animatable using Zepto's .animate method, as it uses CSS transitions.
Try something like this: http://jsfiddle.net/DVDLM/5/
function scroll(scrollTo, time) {
var scrollFrom = parseInt(document.body.scrollTop),
i = 0,
runEvery = 5; // run every 5ms
scrollTo = parseInt(scrollTo);
time /= runEvery;
var interval = setInterval(function () {
i++;
document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;
if (i >= time) {
clearInterval(interval);
}
}, runEvery);
}
$('#trigger').click(function () {
scroll('600px', 500);
});
EDIT: I added a runEvery variable, which specifies how often the interval should be ran. The lower this is, the smoother the animation is, but it could affect performance.
EDIT2: I think I misread the question. Here is the answer to the new question:
$.zepto.scrollTop = function (pixels) {
this[0].scrollTop = pixels;
};
dont want to steel nobody work so here is the short answer
Porting from jQuery to Zepto
Use the DOM native scrollTop property:
$('#el')[0].scrollTop = 0;
(function ($) {
['width', 'height'].forEach(function(dimension) {
var offset, Dimension = dimension.replace(/./, function(m) { return m[0].toUpperCase() });
$.fn['outer' + Dimension] = function(margin) {
var elem = this;
if (elem) {
var size = elem[dimension]();
var sides = {'width': ['left', 'right'], 'height': ['top', 'bottom']};
sides[dimension].forEach(function(side) {
if (margin) size += parseInt(elem.css('margin-' + side), 10);
});
return size;
}
else {
return null;
}
};
});
["Left", "Top"].forEach(function(name, i) {
var method = "scroll" + name;
function isWindow( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
}
function getWindow( elem ) {
return isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
}
$.fn[method] = function( val ) {
var elem, win;
if (val === undefined) {
elem = this[0];
if (!elem) {
return null;
}
win = getWindow(elem);
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[i ? "pageYOffset" : "pageXOffset"] :
win.document.documentElement[method] ||
win.document.body[method] :
elem[method];
}
// Set the scroll offset
this.each(function() {
win = getWindow(this);
if (win) {
var xCoord = !i ? val : $(win).scrollLeft();
var yCoord = i ? val : $(win).scrollTop();
win.scrollTo(xCoord, yCoord);
}
else {
this[method] = val;
}
});
}
});
})(Zepto);
The answer is simple, Zepto dose not use timeout style animation, it uses css3, so here is a basic implementation for a scroll function:
HTML:
Animated Scroll
Hello You
​
CSS:
#page { height:5000px; position:relative; }
#element { position:absolute; top:600px }
JS:
function scroll(selector, animate, viewOffset) {
$('body').scrollToBottom (600, '800');
}
$('#trigger').click(function(e) {
e.preventDefault();
scroll( $('#element'), true, 30 );
});
$.fn.scrollToBottom = function(scrollHeight ,duration) {
var $el = this;
var el = $el[0];
var startPosition = el.scrollTop;
var delta = scrollHeight - startPosition;
var startTime = Date.now();
function scroll() {
var fraction = Math.min(1, (Date.now() - startTime) / duration);
el.scrollTop = delta * fraction + startPosition;
if(fraction < 1) {
setTimeout(scroll, 10);
}
}
scroll();
};
​
Note that version 1.0 of Zeptos now supports scrollTop(). See Documentation:
http://zeptojs.com/#scrollTop

How to know browser idle time?

How can I track the browser idle time? I am using IE8.
I am not using any session management and don't want to handle it on server side.
Here is pure JavaScript way to track the idle time and when it reach certain limit do some action:
var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsTimer = null;
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
alert("Time expired!");
document.location.href = "logout.html";
}
}
#SecondsUntilExpire { background-color: yellow; }
You will be auto logged out in <span id="SecondsUntilExpire"></span> seconds.
​This code will wait 60 seconds before showing alert and redirecting, and any action will "reset" the count - mouse click, mouse move or key press.
It should be as cross browser as possible, and straight forward. It also support showing the remaining time, if you add element to your page with ID of SecondsUntilExpire.
The above code should work fine, however has several downsides, e.g. it does not allow any other events to run and does not support multiply tabs. Refactored code that include both of these is following: (no need to change HTML)
var IDLE_TIMEOUT = 60; //seconds
var _localStorageKey = 'global_countdown_last_reset_timestamp';
var _idleSecondsTimer = null;
var _lastResetTimeStamp = (new Date()).getTime();
var _localStorage = null;
AttachEvent(document, 'click', ResetTime);
AttachEvent(document, 'mousemove', ResetTime);
AttachEvent(document, 'keypress', ResetTime);
AttachEvent(window, 'load', ResetTime);
try {
_localStorage = window.localStorage;
}
catch (ex) {
}
_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function GetLastResetTimeStamp() {
var lastResetTimeStamp = 0;
if (_localStorage) {
lastResetTimeStamp = parseInt(_localStorage[_localStorageKey], 10);
if (isNaN(lastResetTimeStamp) || lastResetTimeStamp < 0)
lastResetTimeStamp = (new Date()).getTime();
} else {
lastResetTimeStamp = _lastResetTimeStamp;
}
return lastResetTimeStamp;
}
function SetLastResetTimeStamp(timeStamp) {
if (_localStorage) {
_localStorage[_localStorageKey] = timeStamp;
} else {
_lastResetTimeStamp = timeStamp;
}
}
function ResetTime() {
SetLastResetTimeStamp((new Date()).getTime());
}
function AttachEvent(element, eventName, eventHandler) {
if (element.addEventListener) {
element.addEventListener(eventName, eventHandler, false);
return true;
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, eventHandler);
return true;
} else {
//nothing to do, browser too old or non standard anyway
return false;
}
}
function WriteProgress(msg) {
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = msg;
else if (console)
console.log(msg);
}
function CheckIdleTime() {
var currentTimeStamp = (new Date()).getTime();
var lastResetTimeStamp = GetLastResetTimeStamp();
var secondsDiff = Math.floor((currentTimeStamp - lastResetTimeStamp) / 1000);
if (secondsDiff <= 0) {
ResetTime();
secondsDiff = 0;
}
WriteProgress((IDLE_TIMEOUT - secondsDiff) + "");
if (secondsDiff >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
ResetTime();
alert("Time expired!");
document.location.href = "logout.html";
}
}
The refactored code above is using local storage to keep track of when the counter was last reset, and also reset it on each new tab that is opened which contains the code, then the counter will be the same for all tabs, and resetting in one will result in reset of all tabs. Since Stack Snippets do not allow local storage, it's pointless to host it there so I've made a fiddle:
http://jsfiddle.net/yahavbr/gpvqa0fj/3/
Hope this is what you are looking for
jquery-idletimer-plugin
Too late to reply, but this might help someone to write clean and practical solution. This is an ideal solution, when you do not need to display time left for session expire. Good to ignore setInterval(), which keeps on running the script through out the application running time.
var inactivityTimeOut = 10 * 1000, //10 seconds
inactivitySessionExpireTimeOut = '';
setSessionExpireTimeOut();
function setSessionExpireTimeOut () {
'use strict';
clearSessionExpireTimeout();
inactivitySessionExpireTimeOut = setTimeout(function() {
expireSessionIdleTime();
}, inactivityTimeOut);
}
function expireSessionIdleTime () {
'use strict';
console.log('user inactive for ' + inactivityTimeOut + " seconds");
console.log('session expired');
alert('time expired');
clearSessionExpireTimeout();
document.location.href = "logout.html";
}
function clearSessionExpireTimeout () {
'use strict';
clearTimeout(inactivitySessionExpireTimeOut);
}
Running example: Timeout alert will be popped up in 10 seconds
Here's an approach using jquery as I needed to preserve existing keyboard events on the document.
I also needed to do different things at different idle times so I wrapped it in a function
var onIdle = function (timeOutSeconds,func){
//Idle detection
var idleTimeout;
var activity=function() {
clearTimeout(idleTimeout);
console.log('to cleared');
idleTimeout = setTimeout(func, timeOutSeconds * 1000);
}
$(document).on('mousedown mousemove keypress',activity);
activity();
}
onIdle(60*60,function(){
location.reload();
});
onIdle(30,function(){
if(currentView!=='welcome'){
loadView('welcome');
}
});
I needed a similar thing and created this :https://github.com/harunurhan/idlejs
It simple, configurable and powerful in a way, without any dependencies. Here's an example.
import { Idle } from 'idlejs/dist';
// with predefined events on `document`
const idle = new Idle()
.whenNotInteractive()
.within(60)
.do(() => console.log('IDLE'))
.start();
You can also use custom event targets and events
const idle = new Idle()
.whenNot([{
events: ['click', 'hover'],
target: buttonEl,
},
{
events: ['click', 'input'],
target: inputEl,
},
])
.within(10)
.do(() => called = true)
.start();
(Written in typescript and compiled to es5)

$ is not a function errors

I'm getting a few Javascript errors and was wondering if anyone could help me out with them. I'm fairly new to js and could really use the help. That being said here is the page with the errors. http://www.gotopeak.com .
Here is the error:
Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function
error is on line 44
Here is the code:
var hoverButton = {
init : function() {
arrButtons = $$('.hover_button');
for (var i=0; i<arrButtons.length; i++) {
arrButtons[i].addEvent('mouseover', hoverButton.setOver);
arrButtons[i].addEvent('mouseout', hoverButton.setOff);
}
},
setOver : function() {
buttonImageSource = this.src;
this.src = buttonImageSource.replace('_off.', '_hover.');
},
setOff : function() {
buttonImageSource = this.src;
if (buttonImageSource.indexOf('_hover.') != -1) {
this.src = buttonImageSource.replace('_hover.', '_off.');
}
}
}
window.addEvent('domready', hoverButton.init);
var screenshots = {
numScreens : 0,
currScreen : 0,
screenContainerAnimation : null,
screenFadeSpeed : 200,
animating : false,
initialized: false,
init : function() {
var arrScreens = $$('#screen_container .screenshot');
screenshots.numScreens = arrScreens.length;
screenshots.screenContainerAnimation = new Fx.Tween('screen_container', {
duration: 300,
transition: Fx.Transitions.Quad.easeInOut
});
var indicatorMold = $('indicatorMold');
for(i=0; i<arrScreens.length; i++) {
var screenShot = arrScreens[i];
screenShot.id = 'screenshot' + (i+1);
var screenIndicator = indicatorMold.clone();
screenIndicator.id = 'indicator' + (i+1);
screenIndicator.inject('screen_indicators');
screenIndicator.href = 'javascript: screenshots.setActiveScreen('+ (i+1)*1 +')';
screenShot.removeClass('hidden');
if (i==0) {
var initialScreenHeight = screenShot.getCoordinates().height;
$('screen_container').setStyle('height', initialScreenHeight);
screenshots.currScreen = 1;
screenIndicator.addClass('active');
}
else {
screenShot.setStyle('opacity',0);
screenShot.setStyle('display','none');
}
} // loop
screenshots.initialized = true;
},
next : function() {
if (screenshots.initialized) {
var nextNum = screenshots.currScreen + 1;
if (nextNum > screenshots.numScreens) {
nextNum = 1;
}
screenshots.setActiveScreen(nextNum);
}
return false;
},
previous : function() {
if (screenshots.initialized) {
var prevNum = screenshots.currScreen - 1;
if (prevNum < 1) {
prevNum = screenshots.numScreens;
}
screenshots.setActiveScreen(prevNum);
}
return false;
},
setActiveScreen : function(screenNum) {
if(screenshots.animating == false) {
screenshots.animating = true;
var currScreen = $('screenshot' + screenshots.currScreen);
var currIndicator = $('indicator' + screenshots.currScreen);
var newScreen = $('screenshot' + screenNum);
var newIndicator = $('indicator' + screenNum);
currScreen.set('tween', {
duration: screenshots.screenFadeSpeed,
transition: Fx.Transitions.Quad.easeInOut,
onComplete: function() {
currIndicator.removeClass('active');
currScreen.setStyle('display','none') ;
}
});
currScreen.tween('opacity', 0);
function resizeScreen() {
newScreen.setStyle('display','block');
var newScreenSize = newScreen.getCoordinates().height;
screenshots.screenContainerAnimation.start('height', newScreenSize);
}
function fadeInNewScreen() {
newScreen.set('tween', {
duration: screenshots.screenFadeSpeed,
transition: Fx.Transitions.Quad.easeInOut,
onComplete: function() {
newIndicator.addClass('active');
screenshots.animating = false;
}
});
newScreen.tween('opacity', 1);
}
resizeScreen.delay(screenshots.screenFadeSpeed);
fadeInNewScreen.delay(screenshots.screenFadeSpeed + 400);
screenshots.currScreen = screenNum;
}
}
}
window.addEvent('load', screenshots.init) ;
I would be very grateful and appreciative of any help that I receive on this issue.
Your page is loading mootools once, jQuery twice and jQuery UI twice. Because both jQuery and mootools define a function named '$', this gives you conflicts.
You can fix this by using a self executing closure that maps the non-conflicted version of '$' to a local '$' variable you can actually use.
(function($) {
// your code
})(document.id);
More information on MooTools' "Dollar Safe Mode" can be found here.
Edit: please ignore. The above answer by igorw is the correct one. Sorry.
Try converting your $ symbols to "jQuery". $ is a shortcut to JQuery. $ is reserved for Prototype in Wordpress.
Edit: you can also try jQuery.noConflict(). It relinquishes control of $ back to JQuery (or the first library that implements it), so it does not cause conflict with other libraries that also implement $.
this is what I did and solved everything, Go to the index.php file, after calling jquery immediately, place <script type="text/javascript">jQuery.noConflict();</script>

Categories