Modernizr complete function seems to be getting ran too early - javascript

I have this javascript:
Modernizr.load([
{
test: Modernizr.canvas,
nope: ['/assets/js/excanvas.js'],
both: ['/assets/js/frank/pentool.js'],
complete : function () {
var cmo = new CutMeOut(settings);
}
}
]);
This loads in excanvas should canvas not be supported and when complete should fire the "complete" function. The CutMeOut class in pentool.js contains code that works with the canvas element. However, IE7 and IE8 are giving this error:
Object doesn't support property or method
If I just load excanvas normally the site works. So, how do I get var cmo = new CutMeOut(settings); to run after excanvas has pollyfilled the problem?
Thanks.

Seems to be work:
Modernizr.load([
{
load: '/assets/js/frank/pentool.js',
complete: function() {
if (!document.createElement('canvas').getContext) {
Modernizr.load('/assets/js/excanvas.js');
} else {
var cmo = new CutMeOut(settings);
}
}
},
{
complete: function() {
if (!document.createElement('canvas').getContext) {
window.addEvent('load', function() {
var cmo = new CutMeOut(settings);
});
}
}
}
]);

Related

AngularJs audio

How do I acknowledge when an audio ends in angular js? I have attached my code. Anyone plz help me.
app.controller("myCtrl",function($scope,ngAudio,$document)
{
$scope.src="aud.mp3";
$scope.play=false;
$scope.play=function()
{
$scope.audio = ngAudio.load('aud.mp3');
$scope.audio.play();
}
$scope.stop=function()
{
$scope.audio = ngAudio.load('aud.mp3');
$scope.audio.pause();
}
$document[0].addEventListener("visibilitychange", function() {
var doucmentHidden = document.hidden;
if (doucmentHidden)
$scope.audio.pause();
else
$scope.audio.play();
}, false);
});
After doing some researches, I didn't find a listener that can tell you when the Aduio ends, but I found two attributes that can give you some useful states :
$scope.audio.paused
or
$scope.audio.canPlay
both of them return booleans, so what you need to do, is to define a function like this :
function listen(audio, callBack) {
if(audio.paused) {
callBack();
} else {
setTimeout(listen);
}
}
The problem with this function is that you need to call it everytime you call the .play() method
$scope.audio.play();
listen($scope.audio, function () {
console.log("ended !!");
});
Note that this is not a good solution, one of the good solutions is to use the native Audio constructor:
$scope.audio = new Audio("aud.mp3");
$scope.audio.onended = function () {
console.log("ended !! ");
}
$scope.audio.play();
Not easy to listen to the ended event unless you edit the module by yourself, I had to edit that module to allow event listener angular.audio.js Line 240
cleverAudioFindingService.find(id)
.then(function(nativeAudio) {
audio = nativeAudio;
audio.addEventListener('canplay', function() {
audioObject.canPlay = true;
});
/*-----*/
audio.addEventListener('ended',function(){
alert('ended');
});
/*-----*/
}, function(error) {
audioObject.error = true;
console.warn(error);
});
Since this is not a good practice, I alternatively used this angular-player

Passing functions between RequireJS files

I've got a file which needs to run on page load (randomise_colors.js), but also needs to be called by another file as part of a callback function (in infinite_scroll.js). The randomise_colors script just loops through a list of posts on the page and assigns each one a color from an array which is used on the front-end.
Infinite Scroll loads new posts in to the DOM on a button click, but because the randomise_colors.js file has already ran on page load, new content loaded is not affected by this so I need it to run again. I'm open to other suggestions if it sounds like I could be tackling the problem in a different way, I'm no JS expert.
Currently I'm getting Uncaught ReferenceError: randomise_colours is not defined referring this line of infinite_scroll.js:
randomise_colours.init();
I'm calling all files that need be loaded on document.ready in app.js
require(['base/randomise-colours', 'base/infinite-scroll'],
function(randomise_colours, infinite_scroll) {
var $ = jQuery;
$(document).ready(function() {
infinite_scroll.init();
randomise_colours.init();
});
}
);
This is infinite_scroll.js which initialises Infinite Scroll and features the callback. The callback function runs whenever new items are loaded in via AJAX using the Infinite Scroll jQuery plugin. I've put asterix around the area where I need to run the randomise_colors.init() function from randomise_colors.js.
define(['infinitescroll'], function() {
var $ = jQuery,
$loadMore = $('.load-more-posts a');
function addClasses() {
**randomise_colours.init();**
};
return {
init: function() {
if($loadMore.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.initInfiniteScroll();
},
initInfiniteScroll: function() {
$('.article-listing').infinitescroll({
navSelector : '.load-more-posts',
nextSelector : '.load-more-posts a',
itemSelector : '.standard-post'
}, function(newItems) {
addClasses();
});
//Unbind the standard scroll-load function
$(window).unbind('.infscr');
//Click handler to retrieve new posts
$loadMore.on('click', function() {
$('.article-listing').infinitescroll('retrieve');
return false;
});
}
};
});
And this is my randomise_colors.js file which runs fine on load, but needs to be re-called again after new content has loaded in.
define([], function() {
var $ = jQuery,
$colouredSlide = $('.image-overlay'),
colours = ['#e4cba3', '#867d75', '#e1ecb9', '#f5f08a'],
used = [];
function pickRandomColour() {
if(colours.length == 0) {
colours.push.apply(colours, used);
used = [];
}
var selected = colours[Math.floor(Math.random() * colours.length)];
var getSelectedIndex = colours.indexOf(selected);
colours.splice(getSelectedIndex, 1);
used.push(selected);
return selected;
};
return {
init: function() {
if($colouredSlide.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.randomiseColours();
},
randomiseColours: function() {
console.log('randomise');
$colouredSlide.each(function() {
var newColour = pickRandomColour();
$(this).css('background', newColour);
});
}
};
});
You would have to reference randomiseColours inside the infiniteScroll file. So you need to change your define function to the following:
define(['infinitescroll', 'randomise-colours'], function(infiniteScroll, randomise_colours)
Remember that when using require you need to reference all variables through the define function, otherwise they will not be recognised.

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

Javascript Conflict ajax mail and scriptaculous

I've added a javascript element I found in a guide. It is as follows
$(document).ready(function ()
{
$('.dropdownbutton').click(function ()
{
$.post("send.php", $(".mycontactform").serialize(), function (data)
{
});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
});
The existing javascript was
function toggleDisplayWait(divId, imgId, durationmSec) {
if(!$(divId).visible()) {
move = Effect.BlindDown;
newImage = "./img/minus.png";
}
else {
move = Effect.BlindUp;
newImage = "./img/plus.png";
}
move(divId, {duration: durationmSec / 1000.0 });
setTimeout(function() { $(imgId).src = newImage; }, durationmSec)
}
function BDEffect(divId, imgId)
{
/* new Effect.BlindDown(element, {duration:3});
}*/
if(!$(divId).visible())
{
move = Effect.BlindDown;
newImage = "./img/feedbacktab_open.png";
setTimeout(function() { $(imgId).src = newImage; }, 0)
}
else
{
move = Effect.BlindUp;
newImage = "./img/feedbacktab.png";
setTimeout(function() { $(imgId).src = newImage; }, 2)
}
move(divId, {duration:2});
/*setTimeout(function() { $(imgId).src = newImage; }, 0)*/
}
</script>
But neither the OLD code nor the NEW code works now.
Error console now reporting "$(divId).visible is not a function" when i try to use the old script
The old code looks like it's using the Prototype framework, and the new code is using jQuery.
When you use the two together, you need to use jQuery's noConflict() so that they don't both try to use the $ variable.
First, after including the jQuery library, add a script like this:
<script>
jQuery.noConflict()
</script>
Then modify your jQuery code to look like this:
jQuery(function ($) {
$('.dropdownbutton').click(function() {
$.post("send.php", $(".mycontactform").serialize(), function(data) {});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
With noConflict, everywhere you want to use jQuery, you must use the jQuery variable instead of $. However, you can still pass $ in as a local variable, and it will not conflict with Prototype.
Also, note that I changed your document.ready(function() { ... }) function into jQuery's shorthand version: jQuery(function() { ... }). The function will also get passed the jQuery object, which I name $ for convenience.

Show GIF-Animation after page request in Firefox

I have a simple throbber, that is automatically shown when an ajax request lasts longer than 3 seconds. This throbber consists mainly of an animated GIF-Image.
Now, I want to use the same throbber also for regular links, meaning that when I click a link and it takes the server more than 3 seconds to respond, the throbber is shown.
Unfortunately, it seems that firefox is unable to play the animation, while it is "reloading" the webpage. The javascript is called and fades the throbber correctly in, but is it not spinning.
How can I make firefox play the GIF-Animation while it is loading?
This is the function:
// Throbber manager
function Throbber() { }
Throbber.prototype = {
image : null,
requests : 0,
requestOpened : function(event) {
if (this.requests == 0) {
this.image.src = 'throbber.gif';
}
this.requests++;
},
requestLoaded : function(event) {
this.requests--;
if (this.requests == 0) {
this.image.src = 'throbber_stopped.gif';
}
},
clicked : function() {
request_manager.abortAll();
},
// Called on window load
attach : function() {
this.image = document.getElementById('throbber');
if (this.image && request_manager) {
request_manager.addEventListener('open', [this, this.requestOpened]);
request_manager.addEventListener('load', [this, this.requestLoaded]);
request_manager.addEventListener('abort', [this, this.requestLoaded]);
this.image.onclick = function() { Throbber.prototype.clicked.apply(throbber, arguments); };
}
}
}
var throbber = new Throbber();
window.addEventListener('load', function() { Throbber.prototype.attach.apply(throbber, arguments); }, false);
function SimpleDemo() { }
SimpleDemo.prototype = {
// The AjaxRequest object
request : null,
// Setup and send the request
run : function() {
this.request = request_manager.createAjaxRequest();
this.request.get = {
one : 1,
two : 2
};
this.request.addEventListener('load', [this, this.ran]);
this.request.open('GET', 'xml.php');
var req = requests[this.request.id];
return setTimeout(function() { req.send(); }, 5000);
},
// Triggered when the response returns
ran : function(event) {
alert(event.request.xhr.responseText);
}
}
If you use jQuery:
$("#throbber").show();
/* Your AJAX calls */
$("#throbber").hide();
Check to see when the DOM is ready before calling all your Ajax stuff.
using Prototype:
document.observe("dom:loaded", function() {
//your code
});
using jQuery:
$(document).ready(function() {
//your code
});
Or Refer this: http://plugins.jquery.com/project/throbber
I just tried my old code and found out that this issue does not exist anymore in Firefox 10.0.2

Categories