Code is Working on Fiddle but not on Website [duplicate] - javascript

This question already has an answer here:
How do I put codes from jsfiddle.net into my website?
(1 answer)
Closed 6 years ago.
This is working fine on Fiddle, but not so fine on my site. I can't seem to figure out the difference.
I've already tried removing the whole Videobox inclusion, and that didn't fix it.
I also realize that jQuery and Mootools is a bit much, but I really like the Videobox, and I really like the audio player.
As far as things working on my site, everything works the way it should, except for the second function in my javascript.
Here's the Fiddle: http://jsfiddle.net/HM8m7/4/
My Site's HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Music</title>
<script type="text/javascript" src="videobox/js/mootools.js"></script>
<script type="text/javascript" src="videobox/js/swfobject.js"></script>
<script type="text/javascript" src="videobox/js/videobox.js"></script>
<link rel="stylesheet" href="videobox/css/videobox.css" type="text/css" media="screen" />
<link rel="stylesheet" href="libs/css/styles.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="src/jquery.ubaplayer.js"></script>
<script>
jQuery.noConflict();
jQuery(function () {
jQuery("#ubaPlayer").ubaPlayer({
codecs: [{
name: "MP3",
codec: 'audio/mpeg;'
}]
});
});
jQuery('a[rel=vidbox]').click(function () {
if (jQuery("#ubaPlayer").ubaPlayer("playing") === true) {
jQuery("#ubaPlayer").ubaPlayer("pause");
}
return false;
});
</script>
</head>
<body>
<div id="content_wrapper">
<div id="table_container">
<table>
<tr>
<th>Title</th>
</tr>
<tr>
<td><div id="ubaPlayer"></div>
<ul class="controls">
<img src="playbtn.png" class="fakeplay" alt="Play Button">The Rainbow Connection (Video)
<ul class="controls">
<li><a class="audioButton" href="mp3/closetoyou.mp3">
Close to You</a></li>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Audio Player Script:
(function($) {
var defaults = {
audioButtonClass: "audioButton",
autoPlay: null,
codecs: [{
name: "OGG",
codec: 'audio/ogg; codecs="vorbis"'
}, {
name: "MP3",
codec: 'audio/mpeg'
}],
continuous: false,
extension: null,
flashAudioPlayerPath: "libs/swf/player.swf",
flashExtension: ".mp3",
flashObjectID: "audioPlayer",
loadingClass: "loading",
loop: false,
playerContainer: "player",
playingClass: "playing",
swfobjectPath: "libs/swfobject/swfobject.js",
volume: 1
},
currentTrack, isPlaying = false,
isFlash = false,
audio, $buttons, $tgt, $el, playTrack, resumeTrack, pauseTrack, methods = {
play: function(element) {
$tgt = element;
currentTrack = _methods.getFileNameWithoutExtension($tgt.attr("href"));
isPlaying = true;
$tgt.addClass(defaults.loadingClass);
$buttons.removeClass(defaults.playingClass);
if (isFlash) {
if (audio) {
_methods.removeListeners(window);
}
audio = document.getElementById(defaults.flashObjectID);
_methods.addListeners(window);
audio.playFlash(currentTrack + defaults.extension);
} else {
if (audio) {
audio.pause();
_methods.removeListeners(audio);
}
audio = new Audio("");
_methods.addListeners(audio);
audio.id = "audio";
audio.loop = defaults.loop ? "loop" : "";
audio.volume = defaults.volume;
audio.src = currentTrack + defaults.extension;
audio.play();
}
},
pause: function() {
if (isFlash) {
audio.pauseFlash();
} else {
audio.pause();
}
$tgt.removeClass(defaults.playingClass);
isPlaying = false;
},
resume: function() {
if (isFlash) {
audio.playFlash();
} else {
audio.play();
}
$tgt.addClass(defaults.playingClass);
isPlaying = true;
},
playing: function() {
return isPlaying;
}
},
_methods = {
init: function(options) {
var types;
//set defaults
$.extend(defaults, options);
$el = this;
//listen for clicks on the controls
$(".controls").bind("click", function(event) {
_methods.updateTrackState(event);
return false;
});
$buttons = $("." + defaults.audioButtonClass);
types = defaults.codecs;
for (var i = 0, ilen = types.length; i < ilen; i++) {
var type = types[i];
if (_methods.canPlay(type)) {
defaults.extension = [".", type.name.toLowerCase()].join("");
break;
}
}
if (!defaults.extension || isFlash) {
isFlash = true;
defaults.extension = defaults.flashExtension;
}
if (isFlash) {
$el.html("<div id='" + defaults.playerContainer + "'/>");
$.getScript(defaults.swfobjectPath, function() {
swfobject.embedSWF(defaults.flashAudioPlayerPath, defaults.playerContainer, "0", "0", "9.0.0", "swf/expressInstall.swf", false, false, {
id: defaults.flashObjectID
}, _methods.swfLoaded);
});
} else {
if (defaults.autoPlay) {
methods.play(defaults.autoPlay);
}
}
},
updateTrackState: function(evt) {
$tgt = $(evt.target);
if (!$tgt.hasClass("audioButton")) {
return;
}
if (!audio || (audio && currentTrack !== _methods.getFileNameWithoutExtension($tgt.attr("href")))) {
methods.play($tgt);
} else if (!isPlaying) {
methods.resume();
} else {
methods.pause();
}
},
addListeners: function(elem) {
$(elem).bind({
"canplay": _methods.onLoaded,
"error": _methods.onError,
"ended": _methods.onEnded
});
},
removeListeners: function(elem) {
$(elem).unbind({
"canplay": _methods.onLoaded,
"error": _methods.onError,
"ended": _methods.onEnded
});
},
onLoaded: function() {
$buttons.removeClass(defaults.loadingClass);
$tgt.addClass(defaults.playingClass);
audio.play();
},
onError: function() {
$buttons.removeClass(defaults.loadingClass);
if (isFlash) {
_methods.removeListeners(window);
} else {
_methods.removeListeners(audio);
}
},
onEnded: function() {
isPlaying = false;
$tgt.removeClass(defaults.playingClass);
currentTrack = "";
if (isFlash) {
_methods.removeListeners(window);
} else {
_methods.removeListeners(audio);
}
if (defaults.continuous) {
var $next = $tgt.next().length ? $tgt.next() : $(defaults.audioButtonClass).eq(0);
methods.play($next);
}
},
canPlay: function(type) {
if (!document.createElement("audio").canPlayType) {
return false;
} else {
return document.createElement("audio").canPlayType(type.codec).match(/maybe|probably/i) ? true : false;
}
},
swfLoaded: function() {
if (defaults.autoPlay) {
setTimeout(function() {
methods.play(defaults.autoPlay);
}, 500);
}
},
getFileNameWithoutExtension: function(fileName) {
//this function take a full file name and returns an extensionless file name
//ex. entering foo.mp3 returns foo
//ex. entering foo returns foo (no change)
var fileNamePieces = fileName.split('.');
fileNamePieces.pop();
return fileNamePieces.join(".");
}
};
$.fn.ubaPlayer = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return _methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jquery.ubaPlayer");
}
};})(jQuery);
Videobox Script:
var Videobox = {
init: function (options) {
// init default options
this.options = Object.extend({
resizeDuration: 400, // Duration of height and width resizing (ms)
initialWidth: 250, // Initial width of the box (px)
initialHeight: 250, // Initial height of the box (px)
defaultWidth: 625, // Default width of the box (px)
defaultHeight: 350, // Default height of the box (px)
animateCaption: true, // Enable/Disable caption animation
flvplayer: 'swf/flvplayer.swf'
}, options || {});
this.anchors = [];
$A($$('a')).each(function(el){
if(el.rel && el.href && el.rel.test('^vidbox', 'i')) {
el.addEvent('click', function (e) {
e = new Event(e);
e.stop();
this.click(el);
}.bind(this));
this.anchors.push(el);
}
}, this);
this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);
this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);
new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
this.caption = new Element('div').setProperty('id', 'lbCaption').injectInside(this.bottom);
this.number = new Element('div').setProperty('id', 'lbNumber').injectInside(this.bottom);
new Element('div').setStyle('clear', 'both').injectInside(this.bottom);
var nextEffect = this.nextEffect.bind(this);
this.fx = {
overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
center: this.center.effects({duration: 500, transition: Fx.Transitions.sineInOut, onComplete: nextEffect}),
bottom: this.bottom.effect('margin-top', {duration: 400})
};
},
click: function(link) {
return this.open (link.href, link.title, link.rel);
},
open: function(sLinkHref, sLinkTitle, sLinkRel) {
this.href = sLinkHref;
this.title = sLinkTitle;
this.rel = sLinkRel;
this.position();
this.setup();
this.video(this.href);
this.top = Window.getScrollTop() + (Window.getHeight() / 15);
this.center.setStyles({top: this.top+'px', display: ''});
this.fx.overlay.start(0.8);
this.step = 1;
this.center.setStyle('background','#fff url(loading.gif) no-repeat center');
this.caption.innerHTML = this.title;
this.fx.center.start({'height': [this.options.contentsHeight]});
},
setup: function(){
var aDim = this.rel.match(/[0-9]+/g);
this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;
this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;
},
position: function(){
this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.getHeight()+'px'});
},
video: function(sLinkHref){
if (sLinkHref.match(/youtube\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.youtube.com/v/"+this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/metacafe\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('/');
this.videoID = videoId[4];
this.so = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/google\.com\/videoplay/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&hl=en", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/ifilm\.com\/video/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('video/');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.ifilm.com/efp", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
this.so.addVariable("flvbaseclip", this.videoID+"&");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/\.mov/i)) {
this.flash = false;
if (navigator.plugins && navigator.plugins.length) {
this.other ='<object id="qtboxMovie" type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+sLinkHref+'" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
} else {
this.other = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" id="qtboxMovie"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
}
}
else if (sLinkHref.match(/\.wmv/i) || sLinkHref.match(/\.asx/i)) {
this.flash = false;
this.other = '<object NAME="Player" WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" type="application/x-oleobject" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><param NAME="URL" VALUE="'+sLinkHref+'"><param><param NAME="AUTOSTART" VALUE="false"></param><param name="showControls" value="true"></param><embed WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" SRC="'+sLinkHref+'" TYPE="application/x-oleobject" AUTOSTART="false"></embed></object>'
}
else if (sLinkHref.match(/\.flv/i)) {
this.flash = true;
this.so = new SWFObject(this.options.flvplayer+"?file="+sLinkHref, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
}
else {
this.flash = true;
this.videoID = sLinkHref;
this.so = new SWFObject(this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
}
},
nextEffect: function(){
switch (this.step++){
case 1:
this.fx.center.start({'width': [this.options.contentsWidth], 'marginLeft': [this.options.contentsWidth/-2]});
break;
this.step++;
case 2:
this.center.setStyle('background','#fff');
this.flash ? this.so.write(this.center) : this.center.setHTML(this.other) ;
this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height: '0px', marginLeft: this.center.style.marginLeft, width: this.options.contentsWidth+'px',display: ''});
if (this.options.animateCaption){
this.fx.bottom.set(-this.bottom.offsetHeight);
this.bottomContainer.style.height = '';
this.fx.bottom.start(0);
break;
}
this.bottomContainer.style.height = '';
this.step++;
}
},
close: function(){
this.fx.overlay.start(0);
this.center.style.display = this.bottomContainer.style.display = 'none';
this.center.innerHTML = '';
return false;
}};window.addEvent('domready', Videobox.init.bind(Videobox));

Your website JS code needs to wait for DOM ready before the jQuery can find the #ubaPlayer and a[rel=vidbox] elements (This is because your script is declared before the HTML, you could get away with it if your script was defined after the html, albeit not a great idea because you really should have your JavaScript in a external .js file).
So, wrap it with .ready() so that your scripts run after the DOM is ready:
jQuery(document).ready(function () {
jQuery("#ubaPlayer").ubaPlayer({
codecs: [{
name: "MP3",
codec: 'audio/mpeg;'
}]
});
jQuery('a[rel=vidbox]').click(function () {
if (jQuery("#ubaPlayer").ubaPlayer("playing") === true) {
jQuery("#ubaPlayer").ubaPlayer("pause");
}
return false;
});
});
The fiddle has on DOM ready, so it works.

Related

Uncaught TypeError: window.getWidth is not a function . what is this error? how to fix? [duplicate]

This question already has answers here:
Get the size of the screen, current web page and browser window
(20 answers)
Closed 6 days ago.
I see following error for my website (via google Inspect). I need your help to understand the problem and how to fix it?
script.js:137 Uncaught TypeError: window.getWidth is not a function
at Object.check (script.js:137:23)
at Object.initialize (script.js:58:14)
at HTMLDocument.<anonymous> (script.js:442:14)
at n (jquery-1.7.1.min.js:2:14784)
at Object.fireWith (jquery-1.7.1.min.js:2:15553)
at Function.ready (jquery-1.7.1.min.js:2:9773)
at HTMLDocument.B (jquery-1.7.1.min.js:2:14348)
and following is script.js file content:
var TouchMask = {
handlers: [],
isbind: 0,
ontouch: function(){
var result = 1;
TouchMask.handlers.each(function(fn){
result = fn() && result;
});
if(result){
document.removeEvent('touchstart', TouchMask.ontouch);
TouchMask.isbind = 0;
}
},
show: function(){
if(this.isbind){
return false;
}
document.addEvent('touchstart', TouchMask.ontouch);
this.isbind = 1;
},
register: function(handler){
if(typeOf (handler) == 'function' && this.handlers.indexOf(handler) == -1){
this.handlers.push(handler);
}
},
unregister: function(handler){
this.handlers.erase(handler);
}
};
var JawallMenu = {
initialize: function(){
JawallMenu.isAndroidTable = navigator.userAgent.toLowerCase().indexOf('android') > -1 && navigator.userAgent.toLowerCase().indexOf('mobile') == -1;
JawallMenu.isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
JawallMenu.enableTouch();
JawallMenu.check();
window.addEvent('resize', JawallMenu.check);
},
enableTouch: function(){
if (JawallMenu.isTouch){
var jmainnav = $('mainnav');
if(!jmainnav){
return false;
}
var jmenu = jmainnav.getElement('.menu');
if(!jmenu){
return false;
}
var jitems = jmenu.getElements('li.deeper'),
onTouch = function(e){
var i, len, noclick = !this.retrieve('noclick');
e.stopPropagation();
// reset all
for (i = 0, len = jitems.length; i < len; ++i) {
jitems[i].store('noclick', 0);
}
if(noclick){
var jshow = this.addClass('hover').getParents('li.parent').addClass('hover');
jshow = jshow.append([this]);
jitems.each(function (jitem) {
if(!jshow.contains(jitem)){
jitem.removeClass('hover');
}
});
}
this.store('noclick', noclick);
this.focus();
},
onClick = function(e){
e.stopPropagation();
if(this.retrieve('noclick')){
e.preventDefault();
jitems.removeClass('hover');
this.addClass('hover').getParents('li.parent').addClass('hover');
TouchMask.hidetoggle();
TouchMask.show();
} else {
var href = this.getElement('a').get('href');
if(href){
window.location.href = href;
}
}
};
jitems.each(function(jitem){
jitem.addEvent('touchstart', onTouch)
.addEvent('click', onClick)
.store('noclick', 0);
});
JawallMenu.resetmenu = function(){
jitems.store('noclick', 0).removeClass('hover');
return true;
};
TouchMask.register(JawallMenu.resetmenu);
}
},
oldWidth: 0,
check: function(){
var wwidth = window.getWidth();
if(wwidth == JawallMenu.oldWidth){
return;
}
JawallMenu.oldWidth = wwidth;
var jmainnav = $('mainnav');
if(!jmainnav){
return;
}
var jmenuinner = jmainnav.getElement('.menu-inner'),
jmenu = jmainnav.getElement('.menu');
if(!jmenuinner || !jmenu){
return;
}
//check if we have to implement scroll
if (jmenu.offsetWidth > jmenuinner.offsetWidth) {
jmenu.setStyle('float', 'left');
if(!window.menuIScroll){
var jprev = jmainnav.getChildren('.navprev')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navprev'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('prev');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
jnext = jmainnav.getChildren('.navnext')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navnext'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('next');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
checkNav = function (){
if(window.menuIScroll){
jprev.setStyle('display', window.menuIScroll.x >= 0 ? 'none' : 'block');
jnext.setStyle('display', (window.menuIScroll.x <= window.menuIScroll.maxScrollX) ? 'none' : 'block');
}
};
window.menuIScroll = new iScroll(jmenuinner, {
snap: '.menu > li',
hScrollbar: false,
vScrollbar: false,
onRefresh: checkNav,
onScrollEnd: checkNav,
useTransform: false,
onScrollStart: function(){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
},
overflow: ''
});
checkNav();
var jactive = jmenu.getChildren('.active')[0];
if(jactive){
window.menuIScroll.scrollToElement(jactive);
}
}
if (window.menuIScroll) {
window.menuIScroll.refresh();
}
} else {
if (window.menuIScroll) {
window.menuIScroll.scrollTo(0, 0, 0);
}
jmenu.setStyle('float', '');
}
//check if the mobile layout, we change html structure
if(wwidth < 720){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
jmenuinner.setStyle('overflow', 'hidden');
jmenu.getChildren('.deeper > ul').each(function(jsub){
var jitem = jsub.getParent(),
sid = null;
jsub.store('parent', jitem).addClass('jsub').inject(jmainnav).setStyle('position', 'absolute');
if(!JawallMenu.isTouch){
//add mouse event to show/hide sub on desktop
jitem.addEvent('mouseenter', function(e){
clearTimeout(sid);
if(jsub.getStyle('display') != 'none'){
return false;
} else {
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
}
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
jsub.addEvent('mouseenter', function(){
clearTimeout(sid);
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
} else {
//add touch event for touch device
jitem.addEvent('touchstart', function(e){
if(jsub.getStyle('display') == 'none'){
e.stop();
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
TouchMask.hidetoggle();
TouchMask.show();
}
});
}
jitem.addEvent('shide', function(){
clearTimeout(sid);
jsub.setStyle('display', 'none');
jitem.removeClass('over');
JawallMenu.jcitem = null;
}).fireEvent('shide');
});
//only init once
if(!JawallMenu.initTouch && JawallMenu.isTouch){
jmainnav.addEvent('touchstart', function(){
if(JawallMenu.jcitem){
this.store('touchInside', 1);
}
});
TouchMask.hidesub = function(){
if(jmainnav.retrieve('touchInside')){
jmainnav.store('touchInside', 0);
return false;
} else {
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidesub);
TouchMask.hidesub();
JawallMenu.initTouch = 1;
}
} else {
JawallMenu.jcitem = null;
jmainnav.getChildren('.jsub').each(function(jsub){
var jitem = jsub.retrieve('parent');
jitem.removeEvents('mouseenter').removeEvents('mouseleave').removeEvents('touchstart').removeEvents('shide');
jsub.removeProperty('style').removeEvents('mouseenter').removeEvents('mouseleave').removeClass('jsub').inject(jitem);
});
jmenuinner.setStyle('overflow', '');
}
}
};
window.addEventListener('load', function(event) {
if(window.menuIScroll){
window.menuIScroll.refresh();
}
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
});
(function($){
var groups = {
},
handler = function (group, value) {
// ignore user setting for page with fixed option
if ($(document.body).hasClass ('fixed-' + group)){
return;
}
if (value) {
if (groups[group]['type'] == 'toggle') {
var cvalue = $.cookie ('ja-'+group);
if (new RegExp ('(^|\\s)' + value+'(?:\\s|$)').test(cvalue)) {
$(document.body).removeClass (group + '-' + value);
cvalue = cvalue.replace (new RegExp ('(^|\\s)' + value+'(?:\\s|$)', 'g'), '$1');
} else {
$(document.body).addClass (group + '-' + value);
cvalue += ' ' + value;
}
groups[group]['val'] = cvalue;
// update cookie
$.cookie ('ja-'+group, cvalue, {duration: 365, path: '/'});
} else {
// update value & cookie
groups[group]['val'] = value;
$.cookie ('ja-'+group, value, {duration: 365, path: '/'});
// remove current
document.body.className = document.body.className.replace (new RegExp ('(^|\\s)' + group+'-[^\\s]*', 'g'), '$1');
$(document.body).addClass (group + '-' + value);
}
}
// Make the UI reload by trigger resize event for window
$(window).trigger('resize');
};
$.fn.toolbar = function(options){
var defaults = {
group: 'basegrid',
type: 'single',
val: 'm'
},
opt = $.extend(defaults, options);
groups[opt.group] = groups[opt.group] || {};
$.extend(groups[opt.group], {type: opt.type, val: opt.val});
if (!$(document.body).hasClass ('fixed-' + opt.group)){
var value = $.cookie('ja-'+opt.group);
if (value) {
groups[opt.group]['val'] = value; // setting exists, replace the default
// add active class
$(document.body).addClass (groups[opt.group]['val'].replace (/(^|\s)([^\s]+)/g, '$1' + opt.group + '-$2'));
} else if(opt.val) {
handler (opt.group, opt.val);
}
}
// bind event for toolbar
return this.bind('click', function () { handler (opt.group, this.id.replace ('toolbar-' + opt.group + '-', '')); return false; });
};
})(window.$wall || window.jQuery);
(window.$wall || window.jQuery)(document).ready(function ($) {
// enable menu responsive check
if(!($.browser.msie && parseFloat($.browser.version) < 9)){
JawallMenu.initialize();
}
var bindevent = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion) ? 'touchstart' : 'click',
jtoggles = $('.btn-toggle'),
jsidebar = $('#sidebar'),
jtoggleactive = null;
// toggle handle
jtoggles.bind(bindevent, function (event) {
var jactive = $(this),
jparent = jactive.parent();
if (jparent.hasClass('active')) {
jparent.removeClass ('active');
// remove btn-toggle-active
jtoggleactive = null
} else {
// remove other active
jtoggles.parent().removeClass ('active');
// add active for this toggle
jparent.addClass ('active');
// store
jtoggleactive = jactive;
}
if(typeOf (TouchMask.hidesub) == 'function'){
TouchMask.hidesub();
}
TouchMask.show();
return false;
});
jtoggles.parent().bind(bindevent, function(){
if(jtoggleactive){
$('body').data('touchInside', 1);
}
});
TouchMask.hidetoggle = function(){
if (jtoggleactive) {
if($('body').data('touchInside')){
$('body').data('touchInside', 0);
return false;
} else {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidetoggle);
var rfpage = $('#josForm').hasClass('wform') && $('#k2Container').hasClass('k2AccountPage'),
wmobile = false, //normal by default
wmeditor = function(){
if(!wmobile){
var jmce = $('.mceLayout:first');
if(jmce.width() > jmce.closest('.wcontrols').width()){
wmobile = true;
$('table.mceToolbar').each(function(){
$(this).find('> tbody > tr').css('white-space', 'normal').find('td').css({
position: '',
float: 'left',
display: 'inline-block'
});
});
$('.toggle-editor a').trigger('click').delay(300).trigger('click');
}
}
},
sidrfp = setTimeout(wmeditor, 350);
// tracking status of btn-toggle
$(window).resize (function() {
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
if (jtoggleactive) {
if (jtoggleactive.css('display') == 'none') {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
}
}
if (jsidebar.length) {
if(JawallMenu.isTablet){
jsidebar.css({
position: 'fixed',
top: ''
});
}
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
}
if(rfpage){
clearTimeout(sidrfp);
sidrfp = setTimeout(wmeditor, 350);
}
});
// scrollbar for sidebar if exist
if (jsidebar.length) {
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
window.sidebarIScroll = new iScroll(jsidebar.find('.sidebar-inner')[0], {vScrollbar: true, scrollbarClass: 'sidebarTracker', useTransform: false});
if(JawallMenu.isTouch){
var jsbtoggle = jsidebar.find('.btn-toggle:first');
$('<div id="dummy-toggle"></div>').css({
position: 'absolute',
top: 0,
left: 0,
width: jsbtoggle.width(),
height: jsbtoggle.height(),
}).appendTo(document.body).bind(bindevent, function(e){
e.preventDefault();
e.stopPropagation();
jsbtoggle.trigger(bindevent);
});
var lastScroll = 0,
scrollid = null;
$(window).scroll(function(){
lastScroll = $(window).scrollTop();
$('#dummy-toggle').css('top', lastScroll);
if(JawallMenu.isTablet){
clearTimeout(scrollid);
scrollid = setTimeout(function(){
lastScroll = $(window).scrollTop();
scrollid = setTimeout(function(){
if(lastScroll == $(window).scrollTop()){
jsidebar
.css('top', lastScroll + parseFloat(jsidebar.css('top', '').css('top')))
.css('position', 'absolute');
$(document).one('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
}
}, 100);
}, 100);
}
});
}
if(JawallMenu.isTablet && !JawallMenu.isBindTablet){
$(document).on('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
JawallMenu.isBindTablet = 1;
}
}
// check and load typography assert files if nessesary
window.jtypo = jQuery('.item-pagetypography .item-content');
if(!window.jtypo.length){
window.jtypo = jQuery('.typography .itemBody');
}
if(window.jtypo.length){
var css = document.createElement('link');
css.type = 'text/css';
css.rel= 'stylesheet';
css.href= JADef.tplurl + 'css/jtypo.css';
document.getElementsByTagName('head')[0].appendChild(css);
$.getScript(JADef.tplurl + 'js/jtypo.js');
}
});
to understand it better please see the error directly via google inspect at following page:
http://test6.harfrooz.com/117-more/18376-top-20-ufo-sightings
This error made my menus disabled and more issues. I would appreciate for any help to solve this error.
I am fairly certain this has been answered before here.
For normal javascript you can use:
window.innerHeight - the inner height of the browser window (in
pixels)
window.innerWidth - the inner width of the browser window (in
pixels)

webrtc remote video not playing in phonegap ios app?

I have found quite a few similar qustions but they are mainly old and outdated and some of them provided a few pointers which I followed to no avail.
Basically, I'm tring to use webrtc and the phonegap iosrtc plugin to create a simple 2 way video chat.
I followed everything to the letter and I managed to show my own video in the app but the 'remote' video is not showing and I ant figure out what the issue is at all!
I have enabled the debugging in phonegap but I don't get any errors.
This is my complete code:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/webrtc-adapter/out/adapter.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
<!-- custom layout for HTML5 audio/video elements -->
<link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.css">
<script src="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/recordrtc/RecordRTC.js"></script>
<script src="cordova.js"></script>
<script src="ios-websocket-hack.js"></script>
<section class="make-center">
<div>
<label><input type="checkbox" id="record-entire-conference"> Record Entire Conference In The Browser?</label>
<span id="recording-status" style="display: none;"></span>
<button id="btn-stop-recording" style="display: none;">Stop Recording</button>
<br><br>
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Auto Open Or Join Room</button>
</div>
<div id="videos-container" style="margin: 20px 0;"></div>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
</section>
JAVASCRIPT:
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function(isRoomOpened, roomid, error) {
if(isRoomOpened === true) {
showRoomURL(connection.sessionid);
}
else {
disableInputButtons(true);
if(error === 'Room not available') {
alert('Someone already created this room. Please either join or create a separate room.');
return;
}
alert(error);
}
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.join(document.getElementById('room-id').value, function(isJoinedRoom, roomid, error) {
if (error) {
disableInputButtons(true);
if(error === 'Room not available') {
alert('This room does not exist. Please either create it or wait for moderator to enter in the room.');
return;
}
alert(error);
}
});
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExist, roomid, error) {
if(error) {
disableInputButtons(true);
alert(error);
}
else if (connection.isInitiator === true) {
// if room doesn't exist, it means that current user will create the room
showRoomURL(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// by default, socket.io server is assumed to be deployed on your own URL
//connection.socketURL = '/';
// comment-out below line if you do not have your own socket.io server
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketMessageEvent = 'video-conference-demo';
connection.session = {
audio: true,
video: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var existing = document.getElementById(event.streamid);
if(existing && existing.parentNode) {
existing.parentNode.removeChild(existing);
}
/*event.mediaElement.removeAttribute('src');
event.mediaElement.removeAttribute('srcObject');
event.mediaElement.muted = true;
event.mediaElement.volume = 0;*/
var video = document.createElement('video');
try {
video.setAttributeNode(document.createAttribute('autoplay'));
video.setAttributeNode(document.createAttribute('playsinline'));
} catch (e) {
video.setAttribute('autoplay', true);
video.setAttribute('playsinline', true);
}
if(event.type === 'local') {
video.setAttribute('class', 'myvideo');
//$('.yourVideo').attr('src', event.stream);
//$('.yourVideo').attr('id', event.streamid);
alert('local');
video.volume = 0;
try {
video.setAttributeNode(document.createAttribute('muted'));
} catch (e) {
video.setAttribute('muted', true);
}
}
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
video.src = URL.createObjectURL(event.stream);
//var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
var width = $(document).width();
var height = $(document).height();
var mediaElement = getHTMLMediaElement(video, {
/*title: event.userid,*/
buttons: ['full-screen'],
width: 100,
height: 100,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
setTimeout(function() {
// mediaElement.media.play();
video.play();
}, 5000);
mediaElement.id = event.streamid;
// to keep room-id in cache
localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
chkRecordConference.parentNode.style.display = 'none';
if(chkRecordConference.checked === true) {
btnStopRecording.style.display = 'inline-block';
recordingStatus.style.display = 'inline-block';
var recorder = connection.recorder;
if(!recorder) {
recorder = RecordRTC([event.stream], {
type: 'video'
});
recorder.startRecording();
connection.recorder = recorder;
}
else {
recorder.getInternalRecorder().addStreams([event.stream]);
}
if(!connection.recorder.streams) {
connection.recorder.streams = [];
}
connection.recorder.streams.push(event.stream);
recordingStatus.innerHTML = 'Recording ' + connection.recorder.streams.length + ' streams';
}
if(event.type === 'local') {
connection.socket.on('disconnect', function() {
if(!connection.getAllParticipants().length) {
location.reload();
}
});
}
};
var recordingStatus = document.getElementById('recording-status');
var chkRecordConference = document.getElementById('record-entire-conference');
var btnStopRecording = document.getElementById('btn-stop-recording');
btnStopRecording.onclick = function() {
var recorder = connection.recorder;
if(!recorder) return alert('No recorder found.');
recorder.stopRecording(function() {
var blob = recorder.getBlob();
invokeSaveAsDialog(blob);
connection.recorder = null;
btnStopRecording.style.display = 'none';
recordingStatus.style.display = 'none';
chkRecordConference.parentNode.style.display = 'inline-block';
});
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
connection.onMediaError = function(e) {
if (e.message === 'Concurrent mic process limit.') {
if (DetectRTC.audioInputDevices.length <= 1) {
alert('Please select external microphone. Check github issue number 483.');
return;
}
var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
connection.mediaConstraints.audio = {
deviceId: secondaryMic
};
connection.join(connection.sessionid);
}
};
// ..................................
// ALL below scripts are redundant!!!
// ..................................
function disableInputButtons(enable) {
document.getElementById('room-id').onkeyup();
document.getElementById('open-or-join-room').disabled = !enable;
document.getElementById('open-room').disabled = !enable;
document.getElementById('join-room').disabled = !enable;
document.getElementById('room-id').disabled = !enable;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
var txtRoomId = document.getElementById('room-id');
txtRoomId.value = roomid;
txtRoomId.onkeyup = txtRoomId.oninput = txtRoomId.onpaste = function() {
localStorage.setItem(connection.socketMessageEvent, document.getElementById('room-id').value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(roomid, function(isRoomExist) {
if (isRoomExist) {
connection.join(roomid);
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
// detect 2G
if(navigator.connection &&
navigator.connection.type === 'cellular' &&
navigator.connection.downlinkMax <= 0.115) {
alert('2G is not supported. Please use a better internet service.');
}
window.cordova.InAppBrowser.open(" https://vps267717.ovh.net/webrtc", "_blank", "location=no,toolbar=yes");
As you can see in my code, I have this:
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
But this never fires for some reason!
I have spent the last 3 days trying to figure this out but I haven't had any luck.
So any help and advice would be appreciated.
Thanks in advance.

Delete specific item from local storage

I have a note taking application that im working on . Its made to look like Google Keep
It saves each note in local storage .
I would like to add a delete option to each of the notes (similar to Keep) , but don't know know to do it.
The full code is on my Github page https://github.com/oxhey/keep
HTML :
<!doctype html>
<html>
<head>
<title>Notes</title>
<link href="styles/normalize.css" rel="stylesheet" />
<link href="styles/main.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="window.css">
</head>
<script>
var nw = require('nw.gui');
var win = nw.Window.get();
win.isMaximized = false;
</script>
<body id="gui">
<header class="app-header">
<ul style="margin-top:0.3px">
<li><a href='#' title='Close' id='windowControlClose'></a></li>
<li><a href='#' title='Maximize' id='windowControlMaximize'></a></li>
<li><a href='#' title='Minimize' id='windowControlMinimize'></a></li>
</ul>
<h2 style="margin-top: 10px;margin-left: 20px;color: #fff;">Notes</h2>
</header>
<section class="main-section">
<article class="note add-note">
<h1 class="note-title"></h1>
<p class="note-content">Add a note</p>
</article>
</section>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<script>
// Min
document.getElementById('windowControlMinimize').onclick = function()
{
win.minimize();
};
// Close
document.getElementById('windowControlClose').onclick = function()
{
win.close();
gui.App.closeAllWindows();
};
// Max
document.getElementById('windowControlMaximize').onclick = function()
{
if (win.isMaximized)
win.unmaximize();
else
win.maximize();
};
win.on('maximize', function(){
win.isMaximized = true;
});
win.on('unmaximize', function(){
win.isMaximized = false;
});
</script>
</body>
</html>
Javascript : Main.js
var Strings = {
'en-us': {
DEFAULT_TITLE: "Title",
ADD_NOTE: "Add a note",
SEARCH_PLACEHOLDER: "Search Jin's Keep"
}
};
var Lang = Strings['en-us'];
var Keys = {
ENTER: 10
}
var notes;
function Note(title, content, id) {
Note.numInstances = (Note.numInstances || 0) + 1;
this.id = id ? id : Note.numInstances
this.title = title;
this.content = content;
}
Note.prototype.render = function(index) {
var elem = $('<article class="note" data-index="' + index + '"><h1 class="note-title">' + this.title + '</h1><p class="note-content">' + this.content + '</p></article>');
$(".add-note").after(elem);
}
Note.prototype.toJSON = function() {
return {
id: this.id,
title: this.title,
content: this.content
};
}
function createNote() {
var elem = $(".add-note");
var title = elem.find(".note-title");
var content = elem.find(".note-content");
elem.removeClass("active");
title.hide();
if(title.text() != Lang.DEFAULT_TITLE || content.text() != Lang.ADD_NOTE) {
var id = notes ? notes.length+1 : 1;
var note = new Note(title.text(), content.text(), id);
notes.push(note);
note.render(notes.length-1);
title.text(Lang.DEFAULT_TITLE);
content.text(Lang.ADD_NOTE);
saveNotes();
}
}
function activateNote(note) {
var title = note.find(".note-title");
note.addClass("active");
title.show();
if(isEmpty(title.text())) {
title.text(Lang.DEFAULT_TITLE);
}
}
function saveCurrentNote() {
var noteElement = $(".note.active");
if(noteElement) {
console.log("will save this element: ", noteElement[0]);
var noteIndex = noteElement.attr("data-index");
var note = notes[noteIndex];
note.title = noteElement.find(".note-title").text();
note.content = noteElement.find(".note-content").text();
saveNotes();
deactivateCurrentNote(noteElement);
}
}
function deactivateCurrentNote(note) {
note.removeClass("active");
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE) {
title.hide();
}
$(":focus").blur();
}
function isEmpty(string) {
return string.replace(/\s| /g, '').length == 0;
}
function addTabIndex() {
tabIndex = 3;
$(".note .note-content, .note .note-title").each(function() {
var el = $(this);
el.attr("tabindex", tabIndex++);
});
}
function loadNotes() {
var rawObjects = JSON.parse(localStorage.getItem("notes"));
if(rawObjects && rawObjects.length) {
rawObjects.forEach(function(obj, index) {
obj.__proto__ = Note.prototype;
obj.render(index);
});
return rawObjects;
} else {
console.warn("Couldn't load any note because local storage is empty.");
return [];
}
}
function saveNotes() {
localStorage.setItem("notes", JSON.stringify(notes))
}
$(document).ready(function() {
notes = loadNotes();
addTabIndex();
$(".note").each(function() {
var note = $(this);
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE ) {
title.hide();
}
});
$(".main-section").on("click", ".note .note-content, .note .note-title", function(evt) {
var note = $(this).parent();
activateNote(note);
//console.log('2 - Setting content editable to true', evt);
var noteSection = $(this);
noteSection.prop("contentEditable", true);
});
$(".main-section").on("click", ".note .note-title", function(evt) {
//console.log("3 - Clearing TITLE's text");
var title = $(this);
if(title.text() == Lang.DEFAULT_TITLE) {
title.text("");
}
});
$(".main-section").on("click", ".note .note-content", function(evt) {
//console.log('4 - Clearing CONTENT text', evt);
var content = $(this);
if(content.text() == Lang.ADD_NOTE) {
content.text("");
content.focus();
}
});
$(".main-section").on("click", function(evt) {
if(evt.target == this) {
//console.log('5', evt);
var currentNote = $(".note.active");
if(currentNote.length) {
//console.log('5.a');
if(currentNote.hasClass("add-note")) {
console.log('5 - Creating a new note');
createNote();
} else {
console.log('5 - Saving current note');
saveCurrentNote();
}
if(currentNote.find(".note-title").text() == Lang.DEFAULT_TITLE) {
currentNote.find(".note-title").hide();
}
}
}
});
$(".main-section").on("keypress", ".note .note-content, .note .note-title", function(evt) {
var currentNote = $(".note.active");
console.log('6');
if(evt.which == Keys.ENTER && evt.ctrlKey) {
console.log('2');
if(currentNote.hasClass("add-note")) {
createNote();
} else {
saveCurrentNote();
}
}
});
});
Thanks
Something like this? Use a data attribute on a delete button and pass that as a parameter to a removeNote function.
HTML
<button class="delete" data-id="1">Delete note</button>
JS
$(document).on('click', '.delete', function () {
var id = $(this).data('id');
removeNote(id);
});
function removeNote(id) {
localStorage.removeItem(id);
}

Dynamic dojo/on event

I have a scenario where I want to generalize a page scrolling event on button click using dojo. I haven't been able to make a breakthrough for quite sometime. I'm a DOJO beginner, would like some pointers to get a good solution. I have a fiddle:
http://jsfiddle.net/sacnayak/Ej39D/3/
Pasting the code in again for first reference:
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query"],
function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query) {
function asyncProcess() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("success");
}, 500);
return deferred.promise;
}
var currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
console.log(currentActiveDomButton);
on(dom.byId(currentActiveDomButton.id), "click", function () {
var currentActiveDomNode = query("#screens .screen.active")[0];
console.log(currentActiveDomNode);
var screens = query("#screens .screen");
var nextActiveDiv;
for (i = 0; i < screens.length; i++) {
if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
nextActiveDiv = screens[i];
console.log(nextActiveDiv);
break;
}
}
fx.animateProperty({
node: currentActiveDomNode.id,
duration: 500,
properties: {
opacity: {
start: '1',
end: '0.5'
}
}
}).play();
var process = asyncProcess();
process.then(function () {
style.set(nextActiveDiv.id, "display", "block");
//dojo.byId(currentActiveDomButton.id).style.display = 'none';
dojox.fx.smoothScroll({
node: nextActiveDiv.id,
win: window
}).play();
require(["dojo/dom-class"], function (domClass) {
domClass.remove(currentActiveDomNode.id, "active");
domClass.add(currentActiveDomNode.id, "visited");
domClass.add(nextActiveDiv.id, "active");
currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
console.log(currentActiveDomButton.id);
});
});
});
});
Was able to fix this. Used a dojo.forEach and set up a event listener for every button.
Here's the fiddle:
http://jsfiddle.net/sacnayak/Ej39D/8/
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query", "dojo/dom-class", "dojo/NodeList-traverse"],
function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query, domClass) {
function asyncProcess() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("success");
}, 500);
return deferred.promise;
}
query(".card-footer-button").forEach(function (buttonNode) {
on(dom.byId(buttonNode.id), "click", function () {
//fetch the current active screen
var currentActiveDomNode = query("#screens .screen.active")[0];
var screens = query("#screens .screen");
var nextActiveDiv;
if (buttonNode.value == "Next") {
for (i = 0; i < screens.length; i++) {
if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
if (!domClass.contains(screens[i].id, "visited")) {
nextActiveDiv = screens[i];
break;
}
}
}
} else if (buttonNode.value == "Edit") {
nextActiveDiv = query("#" + buttonNode.id).parent(".screen")[0];
/*fx.animateProperty({
node: nextActiveDiv.id,
duration: 500,
properties: {
opacity: {
start: '0.5',
end: '1'
}
}
}).play();*/
}
fx.animateProperty({
node: currentActiveDomNode.id,
duration: 500,
properties: {
opacity: {
start: '1',
end: '0.5'
}
}
}).play();
var process = asyncProcess();
process.then(function () {
style.set(nextActiveDiv.id, "display", "block");
dojo.byId(buttonNode.id).style.display = 'none';
if(dojo.byId(buttonNode.id + 'Edit') !== null){
dojo.byId(buttonNode.id + 'Edit').style.display = 'block';
}
if (buttonNode.value == "Edit") {
//query(".card-footer-button").forEach(function (buttonArray) {
//if(buttonArray.value == "Next"){
// buttonArray.style.display = "none";
//}
//});
if (buttonNode.id.indexOf("Edit") != -1) {
//console.log('Here');
//console.log('index' + buttonNode.id.indexOf("Edit"));
//console.log('length' + buttonNode.id.length);
var start = 0;
var end = buttonNode.id.indexOf("Edit");
var associatedNextButtonNode = buttonNode.id.substring(start, end);
//console.log(associatedNextButtonNode);
dojo.byId(associatedNextButtonNode).style.display = 'block';
}
}
dojox.fx.smoothScroll({
node: nextActiveDiv.id,
win: window
}).play();
if(nextActiveDiv.style.opacity == '0.5'){
fx.animateProperty({
node: nextActiveDiv.id,
duration: 500,
properties: {
opacity: {
start: '0.5',
end: '1'
}
}
}).play();
}
require(["dojo/dom-class"], function (domClass) {
domClass.remove(currentActiveDomNode.id, "active");
domClass.remove(nextActiveDiv.id, "visited");
if (buttonNode.value == "Next") {
domClass.add(currentActiveDomNode.id, "visited");
}
domClass.add(nextActiveDiv.id, "active");
});
});
});
});
});

jQuery preload only works with ie on refresh

I`m having a problem with ie9 not always loading preloaded images.
Sometimes I haft to refresh the page and then it works.
$jQuery.fn.img_preloader = function(options){
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function(){
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Try commenting the event.complete validation and going directly to the showImage event. It's not the best solution, but worked for me.
$jQuery.fn.img_preloader = function(options)
{
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function()
{
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
imageContainer.operations.showImage(image);
/*if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}*/
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Replace this showimage function..
showImage: function (g) {
d--;
if (g.data.currentImage != undefined) {
g = g.data.currentImage;
}
if (b.delay <= 0) {
g.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed);
}
if (d != 0) {
if (b.delay != 0) {
e.each(function (k, j) {
var h = a(this);
setTimeout(function () {
h.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed)
}, b.delay * (k + 1))
});
if (b.callback != "") {
setTimeout(b.callback, b.delay * e.length)
}
} else {
if (b.callback != "") {
b.callback()
}
}
}
}

Categories