Why jQuery loader not working? - javascript

When my website starts loading it should display loading upto when my website gets loaded. For that I have used jQuery plugin. The following is js file
/*
* jQuery showLoading plugin v1.0
*
* Copyright (c) 2009 Jim Keller
* Context - http://www.contextllc.com
*
* Dual licensed under the MIT and GPL licenses.
*
*/
jQuery.fn.showLoading = function(options) {
var indicatorID;
var settings = {
'addClass': '',
'beforeShow': '',
'afterShow': '',
'hPos': 'center',
'vPos': 'center',
'indicatorZIndex' : 5001,
'overlayZIndex': 5000,
'parent': '',
'marginTop': 0,
'marginLeft': 0,
'overlayWidth': null,
'overlayHeight': null
};
jQuery.extend(settings, options);
var loadingDiv = jQuery('<div></div>');
var overlayDiv = jQuery('<div></div>');
//
// Set up ID and classes
//
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(loadingDiv).attr('id', 'loading-indicator-' + indicatorID );
jQuery(loadingDiv).addClass('loading-indicator');
if ( settings.addClass ){
jQuery(loadingDiv).addClass(settings.addClass);
}
//
// Create the overlay
//
jQuery(overlayDiv).css('display', 'none');
// Append to body, otherwise position() doesn't work on Webkit-based browsers
jQuery(document.body).append(overlayDiv);
//
// Set overlay classes
//
jQuery(overlayDiv).attr('id', 'loading-indicator-' + indicatorID + '-overlay');
jQuery(overlayDiv).addClass('loading-indicator-overlay');
if ( settings.addClass ){
jQuery(overlayDiv).addClass(settings.addClass + '-overlay');
}
//
// Set overlay position
//
var overlay_width;
var overlay_height;
var border_top_width = jQuery(this).css('border-top-width');
var border_left_width = jQuery(this).css('border-left-width');
//
// IE will return values like 'medium' as the default border,
// but we need a number
//
border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width;
border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width;
var overlay_left_pos = jQuery(this).offset().left + parseInt(border_left_width);
var overlay_top_pos = jQuery(this).offset().top + parseInt(border_top_width);
if ( settings.overlayWidth !== null ) {
overlay_width = settings.overlayWidth;
}
else {
overlay_width = parseInt(jQuery(this).width()) + parseInt(jQuery(this).css('padding-right')) + parseInt(jQuery(this).css('padding-left'));
}
if ( settings.overlayHeight !== null ) {
overlay_height = settings.overlayWidth;
}
else {
overlay_height = parseInt(jQuery(this).height()) + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom'));
}
jQuery(overlayDiv).css('width', overlay_width.toString() + 'px');
jQuery(overlayDiv).css('height', overlay_height.toString() + 'px');
jQuery(overlayDiv).css('left', overlay_left_pos.toString() + 'px');
jQuery(overlayDiv).css('position', 'absolute');
jQuery(overlayDiv).css('top', overlay_top_pos.toString() + 'px' );
jQuery(overlayDiv).css('z-index', settings.overlayZIndex);
//
// Set any custom overlay CSS
//
if ( settings.overlayCSS ) {
jQuery(overlayDiv).css ( settings.overlayCSS );
}
//
// We have to append the element to the body first
// or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari)
//
jQuery(loadingDiv).css('display', 'none');
jQuery(document.body).append(loadingDiv);
jQuery(loadingDiv).css('position', 'absolute');
jQuery(loadingDiv).css('z-index', settings.indicatorZIndex);
//
// Set top margin
//
var indicatorTop = overlay_top_pos;
if ( settings.marginTop ) {
indicatorTop += parseInt(settings.marginTop);
}
var indicatorLeft = overlay_left_pos;
if ( settings.marginLeft ) {
indicatorLeft += parseInt(settings.marginTop);
}
//
// set horizontal position
//
if ( settings.hPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + ((jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width())) / 2)).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'left' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(jQuery(overlayDiv).css('margin-left'))).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'right' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + (jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(settings.hPos)).toString() + 'px');
}
//
// set vertical position
//
if ( settings.vPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('top', (indicatorTop + ((jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height())) / 2)).toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'top' ) {
jQuery(loadingDiv).css('top', indicatorTop.toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) {
jQuery(loadingDiv).css('top', (indicatorTop + (jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('top', (indicatorTop + parseInt(settings.vPos)).toString() + 'px' );
}
//
// Set any custom css for loading indicator
//
if ( settings.css ) {
jQuery(loadingDiv).css ( settings.css );
}
//
// Set up callback options
//
var callback_options =
{
'overlay': overlayDiv,
'indicator': loadingDiv,
'element': this
};
//
// beforeShow callback
//
if ( typeof(settings.beforeShow) == 'function' ) {
settings.beforeShow( callback_options );
}
//
// Show the overlay
//
jQuery(overlayDiv).show();
//
// Show the loading indicator
//
jQuery(loadingDiv).show();
//
// afterShow callback
//
if ( typeof(settings.afterShow) == 'function' ) {
settings.afterShow( callback_options );
}
return this;
};
jQuery.fn.hideLoading = function(options) {
var settings = {};
jQuery.extend(settings, options);
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(document.body).find('#loading-indicator-' + indicatorID ).remove();
jQuery(document.body).find('#loading-indicator-' + indicatorID + '-overlay' ).remove();
return this;
};
In html file I used the script as following..
<script type="text/javascript">
$(document).ready(
function()
{
jQuery('#activity_pane').showLoading(
{
'afterShow':
function()
{
setTimeout( "jQuery('#activity_pane').hideLoading()", 3000 );
}
}
);
}
);
</script>
and my div tag is as following..
<div id="activity_pane">
Here is where we will load something via ajax.
<br />
This container <b>must</b> have an id attribute
</div>
but i am getting error as following..
TypeError: jQuery(...).showLoading is not a function
function()
Please help me to solve this issue.
Thanks in advance.

First things first.
The event below is fired after the whole content is loaded on the page:
$(document).ready()
So, why would you attach a loading window to this event as it was supposed to be shown while the page gets loaded?
Checking the plugin website, the example given is to attach it to a click event, so the loading window will popup while the AJAX call is being executed.
Unless your whole page is loaded from an AJAX call started on a click event, I'm pretty sure their example wouldn't fit your idea.

Related

jQuery.Popup is not a constructor & Query is not defined(anonymous function)

I've come to the tail end of a module I'm creating for Magento 2 but I'm having trouble getting it to render on the screen. This code has worked on other sites in the past but there seems to be an issue stopping this one from working. The issue seems to be with my code "var popup = new jQuery.Popup(poOptions);" note being recognized as a constructor.
I read through a few similar posts (like this one WOW is not a constructor) but I can't seem to figure out what the issue is still
The jquery plugin I'm utilizing originates from https://github.com/Toddish/Popup, on our website page here https://76a8q06e6vrsbggs.mojostratus.io/catalog/product/view/id/44/s/2018-official-joules-vest/category/5/
The idea is you add some custom text in the field labeled "personalize", click the preview button, and a window opens up showing the custom text you had on the item. The link the code constructs works fine, its the actual popup that renders the image that is the issue. I'm adding the code that seems relevant to the situation, hope someone can help me out here this has been a headscratcher especially since it works a lot of times, but if you refresh enough it breaks and I don't understand why.
Can anyone out there help me figure this out?
EDIT: I removed an additional jQuery Library call that seemed to be triggering some errors, having said that, it's still inconsistently working because sometimes I get the "(index):2025 Uncaught ReferenceError: jQuery is not defined" error.
<script type="text/javascript">
var liquifireArguments = [];
/*-------------------------------
POPUP.JS
Simple Popup plugin for jQuery
#author Todd Francis
#version 2.2.3
-------------------------------*/
;(function($, window){
'use strict';
/**
* Popup jQuery method
*
* #param {Object} settings
* #return {Object}
*/
$.fn.popup = function(settings){
var selector = this.selector,
popup = new $.Popup(settings);
$(document)
.on('click.popup', selector, function(e){
var content = settings && settings.content
? settings.content
: $(this).attr('href');
e.preventDefault();
popup.open(content, undefined, this);
});
return this.each(function(){
$(this)
.data('popup', popup);
});
};
/**
* Main Popup Class
*
* #param {Object} settings
*/
$.Popup = function(settings)
{
var p = this,
defaults = {
// Markup
backClass : 'popup_back',
backOpacity : 0.7,
containerClass : 'popup_cont',
closeContent : '<div class="popup_close">×</div>',
markup : '<div class="popup"><div class="popup_content"/></div>',
contentClass : 'popup_content',
preloaderContent : '<p class="preloader"> </p>',
activeClass : 'popup_active',
hideFlash : false,
speed : 200,
popupPlaceholderClass : 'popup_placeholder',
keepInlineChanges : true,
// Content
modal : false,
content : null,
type : 'auto',
width : null,
height : null,
// Params
typeParam : 'pt',
widthParam : 'pw',
heightParam : 'ph',
// Callbacks
beforeOpen : function(type){},
afterOpen : function(){},
beforeClose : function(){},
afterClose : function(){},
error : function(){},
show : function($popup, $back){
var plugin = this;
// Center the popup
plugin.center();
// Animate in
$popup
.animate({opacity : 1}, plugin.o.speed, function(){
// Call the open callback
plugin.o.afterOpen.call(plugin);
});
},
replaced : function($popup, $back){
// Center the popup and call the open callback
this
.center()
.o.afterOpen.call(this);
},
hide : function($popup, $back){
if( $popup !== undefined ){
// Fade the popup out
$popup.animate({opacity : 0}, this.o.speed);
}
},
types : {
inline : function(content, callback){
var $content = $(content);
$content
.addClass(p.o.popupPlaceholderClass);
// If we don't want to keep any inline changes,
// get a fresh copy now
if( !p.o.keepInlineChanges ){
cachedContent = $content.html();
}
callback.call(this, $content.children());
},
image : function(content, callback){
var plugin = this;
var mw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)-100;
var mh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)-100;
var $image = $('<img />')
.one('load', function(){
var img = this;
// Timeout for Webkit
// As the width/height of the image is 0 initially
setTimeout(function(){
callback.call(plugin, img);
}, 0);
})
.one('error', function(){
p.o.error.call(p, content, 'image');
})
.attr('src', content)
.css('max-width',mw)
.css('max-height',mh)
.each(function() {
if( this.complete ){
$(this).trigger('load');
}
});
},
external : function(content, callback){
var $frame = $('<iframe />')
.attr({
src : content,
frameborder : 0,
width : p.width,
height : p.height
});
callback.call(this, $frame);
},
html : function(content, callback){
callback.call(this, content);
},
jQuery : function(content, callback){
callback.call(this, content.html());
},
'function' : function(content, callback){
callback.call(this, content.call(p));
},
ajax : function(content, callback){
$.ajax({
url : content,
success : function(data){
callback.call(this, data);
},
error : function(data){
p.o.error.call(p, content, 'ajax');
}
});
}
}
},
imageTypes = ['png', 'jpg', 'gif'],
type,
cachedContent,
$back,
$pCont,
$close,
$preloader,
$p;
p.ele = undefined;
p.o = $.extend(true, {}, defaults, settings);
/**
* Opens a new popup window
*
* #param {string} content
* #param {string} popupType
* #param {Object} ele
* #return {void}
*/
p.open = function(content, popupType, ele){
// Get the content
content = ( content === undefined || content === '#' )
? p.o.content
: content;
// If no content is set
if( content === null ){
p.o.error.call(p, content, type);
return false;
}
// Was an element passed in?
if( ele !== undefined ){
// Remove current active class
if( p.ele && p.o.activeClass ){
$(p.ele).removeClass(p.o.activeClass);
}
// Record the element
p.ele = ele;
// Add an active class
if( p.ele && p.o.activeClass ){
$(p.ele).addClass(p.o.activeClass);
}
}
// If we're not open already
if( $back === undefined ){
// Create back and fade in
$back = $('<div class="'+p.o.backClass+'"/>')
.appendTo($('body'))
.css('opacity', 0)
.animate({
opacity : p.o.backOpacity
}, p.o.speed);
// If modal isn't specified, bind click event
if( !p.o.modal ){
$back.one('click.popup', function(){
p.close();
});
}
// Should we hide the flash?
if( p.o.hideFlash ){
$('object, embed').css('visibility', 'hidden');
}
// Preloader
if( p.o.preloaderContent ){
$preloader = $(p.o.preloaderContent)
.appendTo($('body'));
}
}
// Get the popupType
popupType = getValue([popupType, p.o.type]);
// If it's at auto, guess a real type
popupType = ( popupType === 'auto' )
? guessType(content)
: popupType;
// Cache the type to use globally
type = popupType;
// Do we have a width set?
p.width = ( p.o.width )
? p.o.width
: null;
// Do we have a height set?
p.height = ( p.o.height )
? p.o.height
: null;
// If it's not inline, jQuery or a function
// it might have params, and they are top priority
if( $.inArray(popupType, ['inline', 'jQuery', 'function']) === -1 ){
var paramType = getParameterByName(p.o.typeParam, content),
paramWidth = getParameterByName(p.o.widthParam, content),
paramHeight = getParameterByName(p.o.heightParam, content);
// Do we have an overriding paramter?
popupType = ( paramType !== null )
? paramType
: popupType;
// Do we have an overriding width?
p.width = ( paramWidth !== null )
? paramWidth
: p.width;
// Do we have an overriding height?
p.height = ( paramHeight !== null )
? paramHeight
: p.height;
}
// Callback
p.o.beforeOpen.call(p, popupType);
// Show the content based
if( p.o.types[popupType] ){
p.o.types[popupType].call(p, content, showContent);
}else{
p.o.types.ajax.call(p, content, showContent);
}
};
/**
* Return the correct value to be used
*
* #param {array} items
* #return {mixed}
*/
function getValue(items){
var finalValue;
$.each(items, function(i, value){
if( value ){
finalValue = value;
return false;
}
});
return finalValue;
}
/**
* Guess the type of content to show
*
* #param {string|Object|function} content
* #return {string}
*/
function guessType(content){
if( typeof content === 'function' ){
return 'function';
} else if( content instanceof $ ){
return 'jQuery';
} else if( content.substr(0, 1) === '#' || content.substr(0, 1) === '.' ){
return 'inline';
} else if( $.inArray(content.substr(content.length - 3), imageTypes) !== -1 ) {
return 'image';
} else if( content.substr(0, 4) === 'http' ) {
return 'external';
}else{
return 'ajax';
}
}
/**
* Shows the content
*
* #param {string} content
* #return {void}
*/
function showContent(content){
// Do we have a preloader?
if( $preloader ){
// If so, hide!
$preloader.fadeOut('fast', function(){
$(this).remove();
});
}
// Presume we're replacing
var replacing = true;
// If we're not open already
if( $pCont === undefined ){
// We're not replacing!
replacing = false;
// Create the container
$pCont = $('<div class="'+p.o.containerClass+'">');
// Add in the popup markup
$p = $(p.o.markup)
.appendTo($pCont);
// Add in the close button
$close = $(p.o.closeContent)
.one('click', function(){
p.close();
})
.appendTo($pCont);
// Bind the resize event
$(window).resize(p.center);
// Append the container to the body
// and set the opacity
$pCont
.appendTo($('body'))
.css('opacity', 0);
}
// Get the actual content element
var $pContent = $('.'+p.o.contentClass, $pCont);
// Do we have a set width/height?
if( p.width ){
$pContent.css('width', p.width, 10);
}else{
$pContent.css('width', '');
var mw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)-100;
$pContent.css('max-width', mw);
}
if( p.height ){
$pContent.css('height', p.height, 10);
}else{
$pContent.css('height', '');
var mh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)-100;
$pContent.css('max-height', mh);
}
// Put the content in place!
if( $p.hasClass(p.o.contentClass) ){
$p
.html(content);
}else{
$p
.find('.'+p.o.contentClass)
.html(content);
}
// Callbacks!
if( !replacing ){
p.o.show.call(p, $pCont, $back);
}else{
p.o.replaced.call(p, $pCont, $back);
}
}
/**
* Close the popup
*
* #return {Object}
*/
p.close = function(){
p.o.beforeClose.call(p);
// If we got some inline content, cache it
// so we can put it back
if(
type === 'inline' &&
p.o.keepInlineChanges
){
cachedContent = $('.'+p.o.contentClass).html();
}
if( $back !== undefined ){
// Fade out the back
$back.animate({opacity : 0}, p.o.speed, function(){
// Clean up after ourselves
p.cleanUp();
});
}
// Call the hide callback
p.o.hide.call(p, $pCont, $back);
return p;
};
/**
* Clean up the popup
*
* #return {Object}
*/
p.cleanUp = function(){
$back
.add($pCont)
.remove();
$pCont = $back = undefined;
// Unbind the resize event
$(window).unbind('resize', p.center);
// Did we hide the flash?
if( p.o.hideFlash ){
$('object, embed').css('visibility', 'visible');
}
// Remove active class if we can
if( p.ele && p.o.activeClass ){
$(p.ele).removeClass(p.o.activeClass);
}
var $popupPlaceholder = $('.'+p.o.popupPlaceholderClass);
// If we got inline content
// put it back
if(
type == 'inline' &&
$popupPlaceholder.length
){
$popupPlaceholder
.html(cachedContent)
.removeClass(p.o.popupPlaceholderClass);
}
type = null;
// Call the afterClose callback
p.o.afterClose.call(p);
return p;
};
/**
* Centers the popup
*
* #return {Object}
*/
p.center = function(){
$pCont.css(p.getCenter());
// Only need force for IE6
$back.css({
height : document.documentElement.clientHeight
});
return p;
};
/**
* Get the center co-ordinates
*
* Returns the top/left co-ordinates to
* put the popup in the center
*
* #return {Object} top/left keys
*/
p.getCenter = function(){
var pW = $pCont.children().outerWidth(true),
pH = $pCont.children().outerHeight(true),
wW = document.documentElement.clientWidth,
wH = document.documentElement.clientHeight;
return {
top : wH * 0.5 - pH * 0.5,
left : wW * 0.5 - pW * 0.5
};
};
/**
* Get parameters by name
* #param {string} name
* #return {null|string} null if not found
*/
function getParameterByName(name, url){
var match = new RegExp('[?&]'+name+'=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
};
}(jQuery, window));
</script>
/*optionId = InputId Of Personalization field*/
var personalizedField = document.getElementsByClassName('product-custom-option')[0].id;
//!TODO: String/VAR TO ARRAY
// console.log('personalizedField: ' + personalizedField);
arguments = {optionId:personalizedField, argument:'<?= $liquifire_argument ?>'};
// console.log("arguments: " + arguments);
liquifireArguments.push(arguments);
jQuery( document ).ready(function(){
function lpiEncode(str) {
var encoded = str;
encoded = encoded.replace(/&/g, "U0026amp;");
encoded = encoded.replace(/'/g, "U0027");
encoded = encoded.replace(/\(/g, "U0026lp;");
encoded = encoded.replace(/\)/g, "U0026rp;");
encoded = encoded.replace(/\[/g, "U005B");
encoded = encoded.replace(/\]/g, "U005D");
encoded = encoded.replace(/\`/g, "U0060");
encoded = encoded.replace(/\+/g, "%2b");
return encoded;
}
jQuery('#product-options-wrapper').append('<div class="lp-box"><button type="button" title="Preview" class="button" id="liquifire-preview"><span><span>Preview</span></span></button></div>');
jQuery('#liquifire-preview').click(function(){
//jQuery('.mousetrap').addClass('liquidpixels');
var liquifireUrl = 'https://urm.liquifire.com/urm';
var liquifireChain = '<?= $image_chain ?>';
var imageUrl = liquifireUrl + '?';
// console.log("liquifireUrl: " + liquifireUrl);
// console.log("liquifireChain: " + liquifireChain);
// console.log("imageUrl: " + imageUrl);
jQuery.each(liquifireArguments, function(){
optionValue = document.getElementById(this.optionId).value;
if( optionValue !== ''){
var argument = this.argument;
if(liquifireArguments.indexOf(this) === 0){
imageUrl += 'set=';
}else{
imageUrl += ',';
}
// Add variable and value
imageUrl += argument + '[' + lpiEncode(optionValue) + ']';
}
});
if(document.getElementById('select_label_color')) {
lpcolor = document.getElementById('select_label_color').textContent.toLowerCase();
if( lpcolor !== ''){
imageUrl += ',selColor[' + lpcolor + '.jpg]';
}
}
// Zoom Url
zoomUrl = imageUrl + '&call=url[file:' + liquifireChain + ']&scale=size[1000]&sink';
// console.log('zoomUrl: '+ zoomUrl);
// Add image chain
imageUrl += '&call=url[file:' + liquifireChain + ']&scale=size[900]&sink';
// console.log('imageUrl: '+ imageUrl);
var poOptions = { type : 'image' };
var popup = new jQuery.Popup(poOptions);
popup.open(zoomUrl);
});
});
</script>
This seems to be a relatively common Magento 2 issue for custom modules. There are a number of solutions out there that may be better than this one, having said that, the one I found here https://www.offset101.com/magento-2-x-fix-uncaught-referenceerror-jquery-not-definedanonymous-function-javascript-message/ was the most straight forward.
Wrapping my code in the below require function did the trick.
require(['jquery'],function($){
$(document).ready(function(){
alert('YOUR JS HERE');
});
});

how to include a external js function as a internal js function?

i have external js file for circular progress bar.i dont want to have my js file as a external file.i want to have this function also as a internal js function.when i tried including this function i got function is not defined error..
below is the code..
Internal js script...
<script>
( function( $ ){
$( '#circle' ).progressCircle();
$( '#submit' ).click( function() {
$( '#circle' ).progressCircle({
nPercent : 100,
showPercentText : true,
thickness : 4,
circleSize : 50
});
})
})( jQuery );
</script>
My external js file...
( function( $ ){
var ProgressCircle = function( element, options ){
var settings = $.extend( {}, $.fn.progressCircle.defaults,
options );
var thicknessConstant = 0.02;
var nRadian = 0;
computePercent();
setThickness();
var border = ( settings.thickness * thicknessConstant ) + 'em';
var offset = ( 1 - thicknessConstant * settings.thickness * 2 ) +
'em';
var circle = $( element );
var progCirc = circle.find( '.prog-circle' );
var circleDiv = progCirc.find( '.bar' );
var circleSpan = progCirc.children( '.percenttext' );
var circleFill = progCirc.find( '.fill' );
var circleSlice = progCirc.find( '.slice' );
if ( settings.nPercent == 0 ) {
circleSlice.hide();
} else {
resetCircle();
transformCircle( nRadians, circleDiv );
}
setBorderThickness();
updatePercentage();
setCircleSize();
function computePercent () {
settings.nPercent > 100 || settings.nPercent < 0 ? settings.nPercent
= 0 : settings.nPercent;
nRadians = ( 360 * settings.nPercent ) / 100;
}
function setThickness () {
if ( settings.thickness > 10 ) {
settings.thickness = 10;
} else if ( settings.thickness < 1 ) {
settings.thickness = 1;
} else {
settings.thickness = Math.round( settings.thickness );
}
}
function setCircleSize ( ) {
progCirc.css( 'font-size', settings.circleSize + 'px' );
}
function transformCircle ( nRadians, cDiv ) {
var rotate = "rotate(" + nRadians + "deg)";
cDiv.css({
"-webkit-transform" : rotate,
"-moz-transform" : rotate,
"-ms-transform" : rotate,
"-o-transform" : rotate,
"transform" : rotate
});
if( nRadians > 180 ) {
transformCircle( 180, circleFill );
circleSlice.addClass( ' clipauto ');
}
}
function setBorderThickness () {
progCirc.find(' .slice > div ').css({
'border-width' : border,
'width' : offset,
'height' : offset
})
progCirc.find('.after').css({
'top' : border,
'left' : border,
'width' : offset,
'height' : offset
})
}
function resetCircle () {
circleSlice.show();
circleSpan.text( '' );
circleSlice.removeClass( 'clipauto' )
transformCircle( 20, circleDiv );
transformCircle( 20, circleFill );
return this;
}
function updatePercentage () {
settings.showPercentText && circleSpan.text( settings.nPercent + '%'
);
}
};
$.fn.progressCircle = function( options ) {
return this.each( function( key, value ){
var element = $( this );
if ( element.data( 'progressCircle' ) ) {
var progressCircle = new ProgressCircle( this, options );
return element.data( 'progressCircle' );
}
$( this ).append( '<div class="prog-circle">' +
' <div class="percenttext"> </div>' +
' <div class="slice">' +
' <div class="bar"> </div>' +
' <div class="fill"> </div>' +
' </div>' +
' <div class="after"> </div>' +
'</div>');
var progressCircle = new ProgressCircle( this, options );
element.data( 'progressCircle', progressCircle );
});
};
$.fn.progressCircle.defaults = {
nPercent : 50,
showPercentText : true,
circleSize : 100,
thickness : 3
};
})( jQuery );
how to integrate this external js with internal js script and make it work?
Scripts are run linearly. Therefore, if you want to access code in an external script, you'll need to reference it before your internal script.
<script src="external script path"></script>
<script>
your internal script with access to external script
</script>

Trying to access Javascript Object and Your Functions and Returning Undefined

I'm having some problems with the access of this methods and variables, and then i just got return undefined.
Im trying for example:
var slider = animateSlider();
slider.init();
slider.current;
I just want to have the access of all this function's value to manipulate the plugin with his callbacks.
(function($,window,document,undefined)
{
var Arrow = function (pages) {
this.pages = pages;
if(this.pages === 1) {
$('.prev').css({"opacity": "0", "z-index": "-1"});
} else {
$('.prev').css({"opacity": "1", "z-index": "1"});
}
if(this.pages < $('.anim-slider > .anim-slide').length) {
$('.next').css({"opacity": "1", "z-index": "1"});
} else {
$('.next').css({"opacity": "0", "z-index": "-1"});
}
};
/**
* [Create the contructor of animateSlider Plugin]
* #param {object} element [the element the plugin is chain to]
* #param {object} options [plugin's configuration object]
*/
var animateSlider = function(element,options)
{
this.element = element;
this.$element = $(element);
this.options = options;
};
animateSlider.prototype =
{
/**
* [Initialize the plugin]
*/
init : function()
{
//Use Modernizr
this.cssAnimations = Modernizr.cssanimations;
this.cssTransitions = Modernizr.csstransitions;
if (!this.cssAnimations || !this.cssTransitions)
{
throw new Error("Your broswer does not support CSS3 Animations or Transitions");
}
this.config = $.extend({},this.defaults,this.options);
this.slides = this.$element.children(".anim-slide");
this.slidesCount = this.slides.length;
this.interval = [];//Ovveride config.interval
this.current = 0; //first slide
$('.contador').html(parseInt(this.current + 1) + ' de ' + this.slidesCount);
var $dots = $("<div class=\"anim-dots\"></div>");
var temp = this.slidesCount;
while ( temp --)
{
$dots.append("<span></span>");
}
$dots.appendTo(this.$element);
this.slides.eq(this.current).addClass("anim-slide-this");
this.$dots = this.$element.find(".anim-dots>span");
this.$navNext = $(".anim-arrows-next");
this.$navPrev = $(".anim-arrows-prev");
this.loadEvents();
this.navigate(this.current);
this.updateDots();
this.autoplay();
},
/**
* [Go to current slide and set the proper classes to animate the elements]
* #param {number} page [current slide]
*/
navigate : function(page)
{
//Classes created from animate.css, you can add your own here.
var classes = 'bounce flash pulse rubberBand shake swing tada wobble bounceIn bounceInDown bounceInRight bounceInUp bounceOut bounceOutDown bounceOutLeft bounceOutRight bounceOutUp fadeIn fadeInDown fadeInDownBig fadeInLeft fadeInLeftBig fadeInRight fadeInRightBig fadeInUp fadeInUpBig fadeOut fadeOutDown fadeOutDownBig fadeOutLeft fadeOutLeftBig fadeOutRight fadeOutRightBig fadeOutUp fadeOutUpBig flipInX flipInY flipOutX flipOutY lightSpeedIn lightSpeedOut rotateIn rotateInDownLeft rotateInDownRight rotateInUpLeft rotateInUpRight rotateOut rotateOutDownLeft rotateOutDownRight rotateOutUpLeft rotateOutUpRight slideInDown slideInLeft slideInRight slideOutLeft slideOutRight slideOutUp slideInUp slideOutDown hinge rollIn rollOut fadeInUpLarge fadeInDownLarge fadeInLeftLarge fadeInRightLarge fadeInUpLeft fadeInUpLeftBig fadeInUpLeftLarge fadeInUpRight fadeInUpRightBig fadeInUpRightLarge fadeInDownLeft fadeInDownLeftBig fadeInDownLeftLarge fadeInDownRight fadeInDownRightBig fadeInDownRightLarge fadeOutUpLarge fadeOutDownLarge fadeOutLeftLarge fadeOutRightLarge fadeOutUpLeft fadeOutUpLeftBig fadeOutUpLeftLarge fadeOutUpRight fadeOutUpRightBig fadeOutUpRightLarge fadeOutDownLeft fadeOutDownLeftBig fadeOutDownLeftLarge fadeOutDownRight fadeOutDownRightBig fadeOutDownRightLarge bounceInBig bounceInLarge bounceInUpBig bounceInUpLarge bounceInDownBig bounceInDownLarge bounceInLeft bounceInLeftBig bounceInLeftLarge bounceInRightBig bounceInRightLarge bounceInUpLeft bounceInUpLeftBig bounceInUpLeftLarge bounceInUpRight bounceInUpRightBig bounceInUpRightLarge bounceInDownLeft bounceInDownLeftBig bounceInDownLeftLarge bounceInDownRight bounceInDownRightBig bounceInDownRightLarge bounceOutBig bounceOutLarge bounceOutUpBig bounceOutUpLarge bounceOutDownBig bounceOutDownLarge bounceOutLeftBig bounceOutLeftLarge bounceOutRightBig bounceOutRightLarge bounceOutUpLeft bounceOutUpLeftBig bounceOutUpLeftLarge bounceOutUpRight bounceOutUpRightBig bounceOutUpRightLarge bounceOutDownLeft bounceOutDownLeftBig bounceOutDownLeftLarge bounceOutDownRight bounceOutDownRightBig bounceOutDownRightLarge zoomIn zoomInUp zoomInUpBig zoomInUpLarge zoomInDown zoomInDownBig zoomInDownLarge zoomInLeft zoomInLeftBig zoomInLeftLarge zoomInRight zoomInRightBig zoomInRightLarge zoomInUpLeft zoomInUpLeftBig zoomInUpLeftLarge zoomInUpRight zoomInUpRightBig zoomInUpRightLarge zoomInDownLeft zoomInDownLeftBig zoomInDownLeftLarge zoomInDownRight zoomInDownRightBig zoomInDownRightLarge zoomOut zoomOutUp zoomOutUpBig zoomOutUpLarge zoomOutDown zoomOutDownBig zoomOutDownLarge zoomOutLeft zoomOutLeftBig zoomOutLeftLarge zoomOutRight zoomOutRightBig zoomOutRightLarge zoomOutUpLeft zoomOutUpLeftBig zoomOutUpLeftLarge zoomOutUpRight zoomOutUpRightBig zoomOutUpRightLarge zoomOutDownLeft zoomOutDownLeftBig zoomOutDownLeftLarge zoomOutDownRight zoomOutDownRightBig zoomOutDownRightLarge flipInTopFront flipInTopBack flipInBottomFront flipInBottomBack flipInLeftFront flipInLeftBack flipInRightFront flipInRightBack flipOutTopFront flipOutTopBack flipOutBottomFront flipOutBottomback flipOutLeftFront flipOutLeftBack flipOutRightFront flipOutRightBack strobe shakeX shakeY spin spinReverse slingshot slingshotReverse pulsate heartbeat panic';
var classShow,classHide,delayShow,$next,$current,currentAnimate,nextAnimate;
$current = this.slides.eq(this.current);
currentAnimate = this.elemAnimate(this.current,this.config);
this.current = page;
$next = this.slides.eq(this.current);
nextAnimate = this.elemAnimate(this.current,this.config);
/*=========================================*/
$current.removeClass(" anim-slide-this "+classes);
$current.find("*").removeClass(classes);
//Iterate through a javascript plain object of current and next Slide
$.each(currentAnimate,function(index)
{
if ( index == $current.prop("tagName").toLowerCase() )
{
classHide = $current.data("classHide");
delayShow = $current.data("delayShow");
$current.removeClass(delayShow);
$current.addClass(classHide+" animated");
return false;
}
else
{
classHide = $current.find(index).data("classHide");
delayShow = $current.find(index).data("delayShow");
$current.find(index).removeClass(delayShow);
$current.find(index).addClass(classHide+" animated");
}
});
$.each(nextAnimate,function(index)
{
if ( index == $current.prop("tagName").toLowerCase() )
{
classShow = $next.data("classShow") ;
delayShow = $next.data("delayShow");
$next.removeClass(classes);
$next.addClass(classShow+" "+delayShow+" animated");
return false;
}
else
{
classShow = $next.find(index).data("classShow");
delayShow = $next.find(index).data("delayShow");
$next.find(index).removeClass(classes);
$next.find(index).addClass(classShow+" "+delayShow+" animated ");
}
});
$next.addClass(" anim-slide-this");
/*=========================================*/
this.updateDots();
},
/**
* [Update the dots to the current slide]
*/
updateDots : function()
{
this.$dots.removeClass("anim-dots-this");
this.$dots.eq(this.current).addClass("anim-dots-this");
},
/**
* [If the dots are clicked the autoplay procedure stops
* and you navigate to the current slide]
* #param {number} page [current slide]
*/
dots : function(page)
{
if ( page >= this.slidesCount || page < 0)
{
return false;
}
if (this.config.autoplay)
{
clearTimeout(this.autoplay);
this.config.autoplay = false;
}
this.navigate(page);
},
/**
* [Get the configuration object for each slide element and attach it to elements with $.data]
* #param {number} page [current slide]
* #param {object} config [configuration object]
*/
elemAnimate : function(page,config)
{
if ( typeof config.animations == "object" )
{
if ( this.slidesCount !== Object.keys(config.animations).length )
{
throw new SyntaxError("Slides length and animation Object length must be equal.");
}
//Get the selected Slide configuration object
var animations = config.animations[page];
var $current = this.slides.eq(page);
return $.each(animations,function(index,value)
{
if ( index == $current.prop("tagName").toLowerCase() )
{
if ( $current.data("classShow") == null )
{
if ( typeof value.show === "string" ) { $current.data("classShow",value.show); } else { $current.data("classShow",""); }
if ( typeof value.hide === "string" ) { $current.data("classHide",value.hide); } else { $current.data("classHide",""); }
if ( typeof value.delayShow === "string" ) { $current.data("delayShow",value.delayShow); } else { $current.data("delayShow"," "); }
}
return false;
}
else
{
if ( !$current.find(index)[0] )
{
throw new TypeError("The element \'"+index+"\' does not exist.");
}
if ( $current.find(index).data("classShow") == null )
{
if( typeof value.show === "string" ) { $current.find(index).data("classShow",value.show); } else { $current.find(index).data("classShow"," "); }
if( typeof value.hide === "string" ) { $current.find(index).data("classHide",value.hide); } else { $current.find(index).data("classHide"," "); }
if( typeof value.delayShow === "string" ) { $current.find(index).data("delayShow",value.delayShow); } else { $current.find(index).data("delayShow"," "); }
}
}
});
}
},
/**
* [Call the animDuration for each slide and if the animation time of current slide is bigger than
* config.interval replace it with this.inteval, else leave config.interval with the default value]
*/
autoplay : function()
{
if (this.config.autoplay)
{
var page = this.current;
var that = this;
var loop = function()
{
page = ( page >= that.slidesCount -1 || page < 0 ) ? 0 : page + 1;
that.navigate(page);
that.autoplay();
};
if ( this.interval.length === this.slidesCount )
{
this.autoplayTime = setTimeout(loop,this.interval[page]);
return;
}
this.animDuration(page).done(function(animationTime)
{
if( animationTime >= that.config.interval )
{
that.interval[page] = animationTime;
that.autoplayTime = setTimeout(loop,0);
}
else if( animationTime < that.config.interval )
{
that.interval[page] = that.config.interval;
that.autoplayTime = setTimeout(loop,that.config.interval-animationTime);
}
});
}
},
/**
* [Find the total animation time for the current slide]
* #param {number} page [current slide]
* #return {object} promise [jQuery's Promises to make asynchronous call]
*/
animDuration: function(page)
{
var $slideAnimations = this.slides.eq(page);
var slideAnimationsCount = $slideAnimations.children("*.animated").length;
var animationStart = +new Date();
var promise = new $.Deferred();
var animationTime,count = 0;
$slideAnimations.on("animationend webkitAnimationEnd oanimationend MSAnimationEnd",function()
{
var animationEnd = +new Date();
animationTime = Math.ceil((animationEnd -animationStart)/1000)*1000;
count++;
if (count == slideAnimationsCount)
{
promise.resolve(animationTime);
}
});
return promise;
},
/**
* [Attach events handlers to specific tasks]
*/
loadEvents : function()
{
var that = this;
this.$navNext.on("click",function(event)
{
if(parseInt(that.current + 1) < that.slidesCount) {
if (that.config.autoplay)
{
clearTimeout(that.autoplay);
that.config.autoplay = false;
}
var page = (that.current >= that.slidesCount - 1 ) ? 0 : that.current + 1 ;
that.navigate(page,"next");
Arrow(parseInt(page + 1));
// contador de paginas
$('.contador').html(parseInt(page + 1) + ' de ' + that.slidesCount);
}
event.preventDefault();
});
this.$navPrev.on("click",function(event)
{
if(parseInt(that.current + 1) !== 1) {
if (that.config.autoplay)
{
clearTimeout(that.autoplay);
that.config.autoplay = false;
}
var page = ( that.current === 0 )? that.slidesCount - 1 : that.current - 1;
that.navigate(page,"prev");
Arrow(parseInt(page + 1));
// contador de paginas
$('.contador').html(parseInt(page + 1) + ' de ' + that.slidesCount);
}
event.preventDefault();
});
this.$dots.on("click.slide",function(event)
{
var page = $(this).index();
that.dots(page);
event.preventDefault();
});
},
defaults :
{
autoplay : true,
interval : 5000
}
};
/**
* [Attach the plugin to jQuery's prototype]
* #param {object} options [plugin's configuration object]
* #return {object} this [the jQuery wrapper]
*/
$.fn.animateSlider = function(options)
{
return this.each(function()
{
var instance = $.data(this,"animateSlider");
if (!instance)
{
$.data(this,"animateSlider",new animateSlider(this,options).init());
}
});
};
})(jQuery);
The plugin you are trying to use is this.
README file clearly mentions how to use the plugin.
$(<jquerySelector>).animateSlider();
You cannot just pick and choose the functions you want to access from an IIFE unless it puts variables onto the global scope in case of jquery plugins they usually attach themselves onto the $ scope via $.fn in this case $.fn.animateSlider which means you can only access them via the above syntax.
But if you adamant on accessing variables inside an IIFE.
I will give the steps to access Arrow variable:
Change var Arrow = function (pages) { to Arrow = function (pages).
In main js file. Create an Instance var obj_name = new Arrow(1);
Though I cant think of why you would want to do that and if this is the only way then your design is wrong.

jQuery Hover out-of-line

I have a really simple JavaScript image hover script running on this website, but the hover isn't lining up with the image, and I cant for the life of me figure out why.
http://www.checkmyathletics.com/home/sample-page/
Does my error popout at anyone?
I can post anything thats needs,
thanks
;( function( $, window, undefined ) {
'use strict';
$.HoverDir = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.HoverDir.defaults = {
speed : 300,
easing : 'ease',
hoverDelay : 0,
inverse : false
};
$.HoverDir.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.HoverDir.defaults, options );
// transition properties
this.transitionProp = 'all ' + this.options.speed + 'ms ' + this.options.easing;
// support for CSS transitions
this.support = Modernizr.csstransitions;
// load the events
this._loadEvents();
},
_loadEvents : function() {
var self = this;
this.$el.on( 'mouseenter.hoverdir, mouseleave.hoverdir', function( event ) {
var $el = $( this ),
$hoverElem = $el.find( 'div' ),
direction = self._getDir( $el, { x : event.pageX, y : event.pageY } ),
styleCSS = self._getStyle( direction );
if( event.type === 'mouseenter' ) {
$hoverElem.hide().css( styleCSS.from );
clearTimeout( self.tmhover );
self.tmhover = setTimeout( function() {
$hoverElem.show( 0, function() {
var $el = $( this );
if( self.support ) {
$el.css( 'transition', self.transitionProp );
}
self._applyAnimation( $el, styleCSS.to, self.options.speed );
} );
}, self.options.hoverDelay );
}
else {
if( self.support ) {
$hoverElem.css( 'transition', self.transitionProp );
}
clearTimeout( self.tmhover );
self._applyAnimation( $hoverElem, styleCSS.from, self.options.speed );
}
} );
},
// credits : http://stackoverflow.com/a/3647634
_getDir : function( $el, coordinates ) {
// the width and height of the current div
var w = $el.width(),
h = $el.height(),
// calculate the x and y to get an angle to the center of the div from that x and y.
// gets the x value relative to the center of the DIV and "normalize" it
x = ( coordinates.x - $el.offset().left - ( w/2 )) * ( w > h ? ( h/w ) : 1 ),
y = ( coordinates.y - $el.offset().top - ( h/2 )) * ( h > w ? ( w/h ) : 1 ),
// the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123);
// first calculate the angle of the point,
// add 180 deg to get rid of the negative values
// divide by 90 to get the quadrant
// add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
direction = Math.round( ( ( ( Math.atan2(y, x) * (180 / Math.PI) ) + 180 ) / 90 ) + 3 ) % 4;
return direction;
},
_getStyle : function( direction ) {
var fromStyle, toStyle,
slideFromTop = { left : '0px', top : '-100%' },
slideFromBottom = { left : '0px', top : '100%' },
slideFromLeft = { left : '-100%', top : '0px' },
slideFromRight = { left : '100%', top : '0px' },
slideTop = { top : '0px' },
slideLeft = { left : '0px' };
switch( direction ) {
case 0:
// from top
fromStyle = !this.options.inverse ? slideFromTop : slideFromBottom;
toStyle = slideTop;
break;
case 1:
// from right
fromStyle = !this.options.inverse ? slideFromRight : slideFromLeft;
toStyle = slideLeft;
break;
case 2:
// from bottom
fromStyle = !this.options.inverse ? slideFromBottom : slideFromTop;
toStyle = slideTop;
break;
case 3:
// from left
fromStyle = !this.options.inverse ? slideFromLeft : slideFromRight;
toStyle = slideLeft;
break;
};
return { from : fromStyle, to : toStyle };
},
// apply a transition or fallback to jquery animate based on Modernizr.csstransitions support
_applyAnimation : function( el, styleCSS, speed ) {
$.fn.applyStyle = this.support ? $.fn.css : $.fn.animate;
el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms' } ) );
},
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.hoverdir = function( options ) {
var instance = $.data( this, 'hoverdir' );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on hoverdir prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for hoverdir instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'hoverdir', new $.HoverDir( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
$(function() {
$(' #da-thumbs > li ').each( function() { $(this).hoverdir({
hoverDelay : 75
}); } );
});
I also use Modernizer (im not familiar with it, but its not paste friendly.)
Thanks a lot
Try adding a margin-top: 20px to your .da-thumbs li a div CSS, that will push it down 20px so that it will cover the image exactly.
.da-thumbs li a div {
margin-top: 20px;
}

uncaught TypeError: Cannot read property "top" of null

I got a pretty annoying javascript error. The world famous:
uncaught TypeError: Cannot read property "top" of null
Here is the code:
$(function() {
var setTitle = function(title, href) {
title = 'Derp: ' + title;
href = href || '';
history.pushState({id: href}, title, href.replace('#', '/'));
document.title = title;
},
scroll = function(url, speed) {
var href = typeof url == 'string' ? url : $(this).attr('href'),
target = $(href),
offset = target.offset(),
title = target.find('h1').text();
if(typeof url == 'number') {
target = [{id:''}];
offset = {top: url};
}
// And move the element
if(offset.top) {
// Set the new URL and title
setTitle(title, href);
// Make sure we're not moving the contact panel
if(target[0].id != 'contact') {
$('html, body').animate({scrollTop: offset.top}, speed);
}
}
return false;
};
// Handle existing URL fragments on load
if(location.pathname.length > 1) {
scroll(location.pathname.replace('/', '#'), 0);
}
$('a#logo').click(function() {
$('html,body').animate({scrollTop: 0});
return false;
});
// Handle internal link clicks
$('a[href^=#]:not(#logo)').click(scroll);
// Close the "Get In Touch" box
var box = $('#contact'),
moveBox = function() {
var closing = $(this).attr('class') == 'close',
amount = closing ? -(box.height() + 20) : 0,
cb = closing ? '' : function() { box.animate({marginTop: -10}, 150); };
box.animate({marginTop: amount}, cb);
};
box.css('margin-top', -(box.height() + 20));
$('#contact a.close, #get-in-touch').click(moveBox);
// Nasty little fix for vertical centering
$('.vertical').each(function() {
$(this).css('margin-top', -($(this).height() / 2));
});
// Work panels
var parent = $('#work'),
panels = parent.children('div');
panels.each(function() {
$(this).css('width', 100 / panels.length + '%');
})
parent.css('width', (panels.length * 100) + '%');
// Bind the keyboards
$(document).keyup(function(e) {
var actions = {
// Left
37: function() {
var prev = panels.filter('.active').prev().not('small');
if(prev.length > 0) {
prev.siblings().removeClass('active');
setTitle(prev.find('h1').text(), prev[0].id);
setTimeout(function() {
prev.addClass('active');
}, 250);
parent.animate({left: '+=100%'}).css('background-color', '#' + prev.attr('data-background'));
}
},
// Right
39: function() {
var next = panels.filter('.active').next();
if(next.length > 0) {
next.siblings().removeClass('active');
setTitle(next.find('h1').text(), next[0].id);
setTimeout(function() {
next.addClass('active');
}, 250);
parent.animate({left: '-=100%'}).css('background-color', '#' + next.attr('data-background'));
}
},
// Down
40: function() {
var w = $(window),
height = w.height() * panels.children('div').length,
h = w.height() + w.scrollTop();
if(h < height) {
scroll(h);
}
},
// Up
38: function() {
var w = $(window);
$('html,body').animate({scrollTop: w.scrollTop() - w.height()});
}
};
// Call a function based on keycode
if(actions[e.which]) {
actions[e.which]();
}
e.preventDefault();
return false;
});
// Fix crazy resize bugs
$(window).resize(function() {
var m = $(this),
h = m.height(),
s = m.scrollTop();
if((h - s) < (h / 2)) {
m.scrollTop(h);
}
//$('html,body').animate({scrollTop: s});
});
// slideshow
var woof = function() {
var slides = $('#molly li'),
active = slides.filter('.active');
if(!active.length) {
active = slides.last();
}
active.addClass('active');
var next = active.next().length ? active.next() : slides.first();
next.css('opacity', 0).addClass('active').animate({opacity: 1}, function() {
active.removeClass('active last-active');
});
};
setInterval(woof, 3000);
// easing
$.easing.swing = function(v,i,s,u,a,l) {
if((i /= a / 2) < 1) {
return u / 2 * (Math.pow(i, 3)) + s;
}
return u / 2 * ((i -= 2) * i * i + 2) + s;
};
// Change the default .animate() time: http://forr.st/~PG0
$.fx.speeds._default = 600;
});
try{Typekit.load()}catch(e){}
Sorry for this long monster but I thought it could be useful for you to see the whole thing. The Error warning shows up in this part:
// And move the element
if(offset.top) {
Uncaught TypeError: Cannot read property 'top' of null
It's line 23 in the code.
That's it. Could you give me a hint on how to solve this problem?
Thank you!
var href = typeof url == 'string' ? url : $(this).attr('href'),
target = $(href), //line 2
offset = target.offset(), //line 3
I believe this must have something to do with line 2, target should be null when error occurs
According to jQuery source, jQuery.fn.offset only returns null if:
the first element in the set doesn't exist (empty set) or
its ownerDocument is falsy (I don't know when that would happen, sorry).
The first option seems more likely, so you should check if target.length > 0 before calling target.offset() and handle the alternative.

Categories