loading my script using getScript - javascript

at first I'm loading all my js script in my header and it's all working properly. But I have one js file that need to be loaded inline/ load it in a certain page only.
this is the js file that I need to load
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
setTimeout(function () {
var el, li, i;
el = document.getElementById('newlist');
if ( el.hasChildNodes() ) {
while ( el.childNodes.length >= 1 ) {
el.removeChild( el.firstChild );
}
}
for (i=0; i<6; i++) {
li = document.createElement('li');
li.innerText = 'Generated row ' + (++generatedCount);
el.insertBefore(li, el.childNodes[0]);
}
myScroll.refresh();
}, 1000);
}
function loaded() {
pullDownEl = document.getElementById('pullDown');
pullDownOffset = pullDownEl.offsetHeight;
myScroll = new iScroll('wrapper', {
//hideScrollbar: false,
//hScrollbar: false, vScrollbar: false, vScroll: false,
useTransition: true,
topOffset: pullDownOffset,
onRefresh: function () {
if (pullDownEl.className.match('loading')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
$('#pullDown').css('display', 'none');
$('#thelist').css('display', 'none');
$('#newlist').css('display', 'inherit');
}
},
onScrollMove: function () {
if (this.y > 5 && !pullDownEl.className.match('flip')) {
pullDownEl.className = 'flip';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = 0;
} else if (this.y < 5 && pullDownEl.className.match('flip')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = -pullDownOffset;
}
},
onScrollEnd: function () {
if (pullDownEl.className.match('flip')) {
pullDownEl.className = 'loading';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';
pullDownAction();
}
}
});
setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
loading it with my other script in my header it works but now I'm using the jquery getScript. It loads the script (using firebug) but when I tried calling the functions inside my js file it give me a two errors
Cannot read property 'offsetHeight' of null
Cannot call method 'refresh' of undefined
This is how I call my js script using getScript
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
pullDownAction();
loaded();
});
});
});
Help anyone

I know this may suggest more work than you want to do, but have you tried doing namespacing? I do not know if this works 100% (as i am not sure of the reasoning why that is not working for you), but have you tried this?
(function( PullDown, $, undefined ) {
//Private variables and this is a great way for minification, you will get the most out of it
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
//... your stuff here
}
function loaded() {
//... more your stuff here
}
}(window.PullDown = window.PullDown || {}, jQuery) // avoids name space collision w/ jQuery
Now do the same things, but with this edit.
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
window.PullDown.pullDownAction();
window.PullDown.loaded();
});
});
});
If i am not mistaken, or have bad copy and paste skills, this should work out just great!

Related

Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery

Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery. i am using jquerycdn variable to pass to the loadscript() when checkjquery() is false. But when i am passing still the jquery CDN is not loading. Same issue facing with the remaining files like bootstrap, D3.js, knockout.js etc. All these file CDN's are kept in one js file.
Please check the below code:-
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
Initialize.prototype.checkJQuery = function () {
if (window.jQuery) {
return true;
} else {
return false;
}
};
if (!this.checkJQuery ()) {
console.log("jquerynot available")
this.loadJQuery ();
if (!this.checkJQuery ()) {
throw "Error loading jquery"
}
} else {
console.log("jquery available")
}
Initialize.prototype.loadJQuery = function () {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function (src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.head.appendChild(my_awesome_script);
}
You need to give jQuery time to load before checking to see that it's loaded. An onload trigger would be better than timeout, but here's your code working.
function Initialize() {
var self = this;
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
if (!this.checkJQuery()) {
console.log("jquery not available")
this.loadJQuery();
setTimeout(function() {
if (!self.checkJQuery()) {
throw "Error loading jquery"
} else {
alert("jQuery loaded!");
}
}, 2500);
} else {
console.log("jquery available")
}
}
Initialize.prototype.checkJQuery = function() {
if (window.jQuery) {
return true;
} else {
return false;
}
};
Initialize.prototype.loadJQuery = function() {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function(src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.body.appendChild(my_awesome_script);
}
var i = new Initialize();
You might also look at this approach.

How do I change a div from popup to slide down?

I'm not very good with javascript and I have this javascript code. When I click on the link the div shows and hides. The problem is the showing effect, it pops up and doesn't look good so I want the div to slide down when it shows.
Here's the code:
<script type="text/javascript">
var s;
ShowHideWidget = {
settings : {
clickHere : document.getElementById('clickHere'),
dropdown_signup : document.getElementById('dropdown_signup')
},
init : function() {
//kick things off
s = this.settings;
this.bindUIActions();
},
bindUIActions : function() {
//Attach handler to the onclick
/*
s.clickHere.onclick = function() {
ShowHideWidget.toggleVisibility(s.showing);
return false;
};
*/
ShowHideWidget.addEvent(s.clickHere, 'click', function() {
ShowHideWidget.toggleVisibility(s.dropdown_signup);
});
},
addEvent : function(element, evnt, funct) {
//addEventListener is not supported in <= IE8
if (element.attachEvent) {
return element.attachEvent('on'+evnt, funct);
} else {
return element.addEventListener(evnt, funct, false);
}
},
toggleVisibility : function(id) {
if(id.style.display == 'block') {
id.style.display = 'none';
} else {
id.style.display = 'block';
};
}
};
(function() {
ShowHideWidget.init();
})();
</script>
You can achieve it by using jquery slideDown and slideUp functions:
Add following code:
toggleVisibility : function(id) {
if( $(id).is(':visible') ){
$(id).slideUp();
} else {
$(id).slideDown();
}
}
DEMO
You'd do well to use something like jQuery's .slideDown function. You'll have to write a lot of code to do this yourself.

Need to Resolve: Uncaught TypeError: Cannot call method 'each' of undefined

I purchased a template from themeforest and am having a "Uncaught TypeError: Cannot call method 'each' of undefined" after I removed two of the three opening sliders. The error slows the page load time down to a crawl however the entire site is functional. Does 'each' reference the 3 original sliders and if so can I edit it to reference the 1 lone slider?
function init_main_slider(target) {
set_height();
jQuery(target).flexslider({
animation : 'fade',
controlNav : true,
directionNav : true,
animationLoop : true,
slideshow : false,
animationSpeed : 500,
useCSS : true,
start : function(slider) {
if(!isMobile) {
slider.slides.each(function(s) {
jQuery(this).find('.animated_item').each(function(n) {
jQuery(this).addClass('animate_item' + n);
});
});
slider.slides.eq(slider.currentSlide).find('.animated_item').each(function(n) {
var show_animation = jQuery(this).attr('data-animation');
jQuery(this).addClass(show_animation);
});
}
else {
slider.find('.counter').find('.num').each(function() {
var container = jQuery(this);
var num = container.attr('data-num');
var content = container.attr('data-content');
count_num(num, content, container, false);
});
}
},
before : function(slider) {
if(!isMobile) {
slider.slides.eq(slider.currentSlide).find('.animated_item').each(function(n) {
var show_animation = jQuery(this).attr('data-animation');
jQuery(this).removeClass(show_animation);
});
slider.slides.find('.animated_item').hide();
var counter_block = slider.slides.eq(slider.currentSlide).find('.counter');
if(counter_block.length > 0) {
setTimeout(function() {
counter_block.find('.num').each(function() {
jQuery(this).html('0');
});
}, 300);
}
}
},
after : function(slider) {
if(!isMobile) {
slider.slides.find('.animated_item').show();
slider.slides.eq(slider.currentSlide).find('.animated_item').each(function(n) {
var show_animation = jQuery(this).attr('data-animation');
jQuery(this).addClass(show_animation);
});
var counter_block = slider.slides.eq(slider.currentSlide).find('.counter');
if(counter_block.length > 0) {
counter_block.find('.num').each(function() {
var container = jQuery(this);
var num = container.attr('data-num');
var content = container.attr('data-content');
count_num(num, content, container, 1500);
});
}
}
}
});
function set_height() {
var w_height = jQuery(window).height();
jQuery(target).height(w_height).find('.slides > li').height(w_height);
}
jQuery(window).resize(function() {
set_height();
});
}
How did you "remove the sliders"? I noticed in the html that the slide still has a class of <li class="slide_3"> which might be causing issues for the plugin. Does it make a difference to remove that or change to just slide or slide_1? If you cant get it to cooperate one idea is that there really is no need for this slider when only have one image so you could count the number of <li> and only use that function when there is more than one image, otherwise insert the single image... something like.
jQuery(function() {
// count the list
var listSize = $(".slides li").size();
if (listSize < 2) {
$('#main_slider').prepend('<img src="images/pic_slider_1_3.png" alt="">')
} else {
init_main_slider('#main_slider');
}
});

How Can I Pre-Load Images So That My Non-Plug-In Slide-Show Timing Is Not Thrown Off In My ASP.NET Web-Pages Site?

Firstly, I have been researching this for a while, but I feel like this problem is a little beyond my abilities to solve on my own. Or at least, beyond my experience at this point, as I have never done this before.
I have a <div> that contains an <img> tag which I use JavaScript to change the source of to create a simple slideshow.
The Simple HTML:
<div id="slideShowWrapper">
<img id="slideShowImage" src="~/Images/City_Images/Okmulgee_Clock_2.jpg" alt="Okmulgee Clock" title="Slide Show Paused" />
</div>
The problem I am having is that when a user visits the site for the first time, the images take too long to load during their first pass through the slideshow, and it throws of the timing of the slideshow. Once the browser has the images cached, it works fine. If there were a way to load all of the pictures before the slideshow starts I believe it would fix the problem. During testing, this problem never arose because the images were already cached by my browser so no excessive loading time was needed.
Here is the JavaScript (jQuery) I use for the slide-show. The images originally come from a server-side database so I use AJAX to get the file name values I need (currently there are only 14 entries/pictures in the database, but this number could increase or decrease as site admins will be able to edit the pictures in the slideshow through a partial CMS). To explain some of the code, this slide-show has the functionality to pause on mouse-over and resume on mouse-out.
jQuery(function ($) {
//Slideshow functionality
var paths = new Array();
var timer = new Array();
var pathsString = "";
var i = 1;
var panel = $("img#slideShowImage");
var fTimer;
var tTimer;
var t2Timer;
var fadingOut = false;
var slideShowOn = false;
var showTimer;
$.ajax({
url: "/AJAX Pages/Compute_Slide_Show.cshtml",
async: false,
type: "GET",
success: function (response) {
paths = response.split("/*\\");
},
error: function (jqXHR, textStatus, error) {
paths[0] = "Okmulgee_Clock_2.jpg";
}
});
if (paths.length > 0) {
panel.attr("src", "/Images/SlideShowPics/" + paths[0])
if (paths.length > 1) {
swapImage();
}
}
else {
panel.attr("src", "/Images/City_Images/Okmulgee_Clock_2.jpg");
}
panel.mouseout(function () {
if (paths.length > 1) {
runSlideShow();
}
});
panel.mouseover(function () {
if (paths.length > 1) {
stopSlideShow();
}
});
function runSlideShow() { //Calls the swapImage function to begin or resume the slide show
if (slideShowOn == false) {
slideShowOn = true;
if (fadingOut == false) {
clearTimeouts();
}
showTimer = setTimeout(swapImage, 1552);
}
};
function stopSlideShow() { //Pauses the slide show
clearTimeout(showTimer);
if (fadingOut == true) {
fTimer = setTimeout(clearTimeouts, 1551);
}
else if (fadingOut == false) {
clearTimeout(tTimer);
clearTimeouts();
}
slideShowOn = false;
};
function swapImage() { //Fades out the slideshow image
tTimer = setTimeout(function () { fadingOut = true }, 4549);
timer[0] = setTimeout(function () { panel.css('opacity', '0.9') }, 4550);
timer[2] = setTimeout(function () { panel.css('opacity', '0.8') }, 4600);
timer[4] = setTimeout(function () { panel.css('opacity', '0.7') }, 4650);
timer[6] = setTimeout(function () { panel.css('opacity', '0.6') }, 4700);
timer[8] = setTimeout(function () { panel.css('opacity', '0.5') }, 4750);
timer[10] = setTimeout(function () { panel.css('opacity', '0.4') }, 4800);
timer[12] = setTimeout(function () { panel.css('opacity', '0.3') }, 4850);
timer[14] = setTimeout(function () { panel.css('opacity', '0.2') }, 4900);
timer[16] = setTimeout(function () { panel.css('opacity', '0.1') }, 4950);
timer[18] = setTimeout(function () { panel.css('opacity', '0') }, 5000);
timer[20] = setTimeout(swapImage2, 5050);
}
function swapImage2() { //Changes and fades in the slideshow image
panel.attr("src", "/Images/SlideShowPics/" + paths[i]);
if (i < paths.length - 1) {
i++;
}
else {
i = 0;
}
timer[21] = setTimeout(function () { panel.css('opacity', '0.1') }, 550);
timer[23] = setTimeout(function () { panel.css('opacity', '0.2') }, 600);
timer[25] = setTimeout(function () { panel.css('opacity', '0.3') }, 650);
timer[27] = setTimeout(function () { panel.css('opacity', '0.4') }, 700);
timer[29] = setTimeout(function () { panel.css('opacity', '0.5') }, 750);
timer[31] = setTimeout(function () { panel.css('opacity', '0.6') }, 800);
timer[33] = setTimeout(function () { panel.css('opacity', '0.7') }, 850);
timer[35] = setTimeout(function () { panel.css('opacity', '0.8') }, 900);
timer[37] = setTimeout(function () { panel.css('opacity', '0.9') }, 950);
timer[39] = setTimeout(function () { panel.css('opacity', '1') }, 1000);
t2Timer = setTimeout(function () { fadingOut = false }, 1050);
timer[41] = setTimeout(swapImage, 1050);
}
function clearTimeouts() { //Clears all slide show timers
for (key in timer) {
clearTimeout(timer[key]);
}
}
});
I tried reading up on this myself, but I am not getting answers that I feel I can adapt to my code. Either that or the solution is above my head.
SO sites I read up on:
Slideshow starts while images are loading but first image isn't displayed until all are downloaded
loading all images before slideshow
If you want to check out the problem yourself, you should be able to get there by visiting this link: http://test.cityofokmulgee.org:54543
Remember that this error is probably only going to naturally show up the first time you load up the page. After that your browser will have cached the images and the load time won't throw off the timing of the slide-show (unless you clear the images from the browser cache, something I have been unsuccessful in doing, myself). Also, I'm not sure if this issue will even show up in Chrome, but I know it does in IE.
Any help is much appreciated, as this is the major bug disallowing this site to go live, and I have never done anything like pre-loading images before, so I don't have any idea where to start.
Additional Info That Might Be Useful:
The contents of the server-side file, Compute_Slide_Show.cshtml (written in C#):
#{
Layout = "";
string fileNames = "";
if(IsAjax)
{
var db = Database.Open("Content");
bool firstRun = true;
foreach (var row in db.Query("SELECT FileOrder, FileName FROM SlideShow WHERE FileName IS NOT NULL AND FileName <> '' ORDER BY FileOrder ASC"))
{
if (firstRun == true)
{
firstRun = false;
fileNames += row.FileName;
}
else
{
fileNames += "/*\\";
fileNames += row.FileName;
}
}
}
else
{
Context.RedirectLocal("~/home.cshtml");
}
#:#fileNames
}
Oh dear, I see a lot of weird stuff in there!
First idea: do you really need to create your own slideshow? In your case I'd rather create the markup with jQuery/AJAX and apply an existing slider, like flexslider, to your images. Why dont you do that?
The second thing, just for the sake of it, is how you solved that opacity dimming. In jQuery, you can easily animate an element via .animate() (which expects a css map) or just use fade(), like so:
function swapImage() { //Fades out the slideshow image
tTimer = setTimeout(function () { fadingOut = true;
panel.stop().fadeTo(500, 0, function() {
// callback after the element has been faded
swapImage2();
});
}, 4549);
}
just besides: setting the opacity via css istn crossbrowser anyways.
To get to your loading thingy, there are several ways how to do this, my advice would be to append an image for each key in paths in a hidden div:
for (var i = 0; i < paths.length; i++) {
$('.hidden').append('<img src="' + paths[i] + '" />');
}
var checkforloaded = setInterval(function() {
var _loaded = 0;
for (var i = 0; i < paths.length; i++) {
var image = $('.hidden').children().eq(i).get(0);
if (image.complete || image.readyState == 'complete' || image.readyState == 4) {
_loaded++;
}
}
if (_loaded === paths.length) {
clearInterval(checkforloaded);
// start the slider
}
}, 80);

What does this BlackBerry Web App Javascript code do?

I know my way around several programming languages but am struggling understanding Javascript and how it's used in mobile apps. I'm developing for BlackBerry and a using the BlackBerry 10 jQuery Mobile Theme. I'm looking at the App.js from the samples and am confused as to what the App object is.
App = {};
App.init = function () {
console.log("App Init");
App.utils.metaHack();
$("#activity").live("pageinit", function(){
App.page.activity.init();
});
$("#bb_activity").live("pageinit", function(){
App.page.bb_activity.init();
});
$("#progressPage").live("pageinit", function(){
App.page.progress.init();
});
$("#sliderPage, #sliderPageDark").live("pageinit", function(){
App.page.slider.init();
});
$("#togglePage, #togglePageDark").live("pageinit", function(){
App.page.toggle.init();
});
$("#actionBarSample").live("pageinit", function() {
App.page.actionBarSample.init();
});
$('#applicationMenu').live("pageinit", function() {
App.page.applicationMenu.init();
});
}
App.utils = {
metaHack: function () {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
}
}
App.page = {
activity: {},
bb_activity: {},
progress: {},
slider: {},
toggle: {},
actionBarSample: {},
applicationMenu: {}
}
App.page.activity.init = function() {
$('#show').on('click', function () {
$.mobile.loading('show');
});
$('#text').on('click', function() {
$.mobile.loading('show', {
text: 'Loading',
textVisible: true,
textonly: true,
theme: 'a'
});
});
$('#swatch-a').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'a'
});
});
$('#swatch-a-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'a'
});
});
$('#swatch-c').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'c'
});
});
$('#swatch-c-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'c'
});
});
$('#hide').on('click', function () {
$.mobile.loading('hide');
});
}
App.page.bb_activity.init = function() {
console.log("bb_activity");
$('#throttle').on('change', function () {
console.log("throttle");
var speed = $('#throttle').val();
$('#speedTest').activityindicator('speed', speed+'s');
});
}
App.page.progress.init = function() {
var p = 0;
var error = pause = false;
function watchProgress() {
if( p > 100 || error || pause) {
return;
}
$('#rogress').progressbar("setValue", p);
p+= 4;
setTimeout(watchProgress, 100);
}
$('#start').on('vclick', function () {
error = false;
watchProgress();
});
$('#error').on('vclick', function () {
$('#rogress').progressbar("setError", error = !error);
});
$('#pause').on('vclick', function () {
$('#rogress').progressbar("pause", pause = !pause);
});
$('#reset').on('vclick', function () {
p = 0;
error = pause = false;
$('#rogress').progressbar("setValue", p);
});
}
App.page.slider.init = function() {
$('#slider-disabled').slider('disable');
$('#slider-disabled-highlight').slider('disable');
}
App.page.toggle.init = function() {
console.log("toggle init");
$('#flip-disabled').slider('disable');
}
App.page.actionBarSample.init = function() {
var $tabo = $("#tover"),
overflowState = $tabo.hasClass("noContent");
$("#left").on("panelbeforeopen", function() {
//Save the state of the overflow button
overflowState = $tabo.hasClass("noContent");
$tabo.addClass("noContent");
})
.on("panelbeforeclose", function() {
//Put the overflow button into the correct state
if(!overflowState) {
$tabo.removeClass("noContent");
}
});
//Handle overflow menu clicks
$(".bb10-panel").bind("vclick", function() {
//Close the panel
$(this).panel("close");
});
$("#left li").bind("vclick", function() {
//Clear the active state from any other buttons that may have been set to active
$(this).siblings().removeClass("ui-btn-active");
//Add the active state to the selected button
$(this).addClass("ui-btn-active");
//Clear the contents of the tab overflow button
//Add class to put the tab overflow icon in the correct position
//Clear the active state from all tab buttons in action bar
$('[data-role="tab"], [data-role="tab-overflow"]').removeClass("active");
});
$(".inBar").bind("vclick", function() {
//Set the active state to the tab in the actionbar
$('#' + this.id.slice(0, 2)).addClass("active");
$tabo.addClass("noContent").empty();
overflowState = true;
});
$(".notInBar").bind("vclick", function() {
//Set the active state to the tab overflow button
$tabo.empty()
.addClass("active")
.html('<img src="img/generic_81_81_placeholder.png" alt=""><p>' + $(this).text() + '</p>')
.removeClass("noContent");
overflowState = false;
});
$("[data-role='tab']").bind("vclick", function() {
//Change page on tab click
if($(this).data("href")) {
$.mobile.changePage( $(this).data("href"), { transition: "slideup"} );
}
});
}
App.page.applicationMenu.init = function() {
if(typeof blackberry != 'undefined'){
blackberry.event.addEventListener('swipedown', function(){
$('#top').panel("open");
});
$('#menuBtn').css('display','none');
}
else{
$('#simulInst').css('display','none');
}
}
App.init();
Is App an object specific to Blackberry? I did some dabbling and made a small app but didn't use App or init anything.
App in this example is defined at the top:
App = {};
So it's just a new plain old JavaScript object (dictionary), which they then define functions and data to it e.g. App.utils = ....
You can try it out on a browser, press F12 and then go to the console (ESC) and type e.g. blah = {} and you will see a new object created with the name blah. Everything is an object in JavaScript apparently.
Read more
http://www.w3schools.com/js/js_objects.asp

Categories

Resources