JavaScript undefined object even it shows data when checking by F12 - javascript

Can any one help with this error.
Here is the code:
$(document).ready(function(){
var certifications = {
nextCert : 0,
data : [
{
"imgSrc" : "http://res.cloudinary.com/sharek/image/upload/v1460011761/UC-PJNHKQ02_r1gjmj.jpg"
},
{
"imgSrc" : "http://res.cloudinary.com/sharek/image/upload/v1460011761/UC-KE5C95GA_aid30q.jpg"
}
],
getNextCert : function(){
if(this.nextCert === this.data.length){
this.nextCert = 0;
}
else{
this.nextCert += 1;
}
return this.nextCert;
},
getCurrentCert : function() {
return this.nextCert;
},
getImgCert : function() {
return this.data[this.getNextCert()];
}
};//certification object
var certContainer = $('#cert-container').html
var templateItem = $(certContainer);
templateItem.find('.img-responsive').attr('src',certifications.getImgCert()['imgSrc']);
$('#nextBtn').click( function(){
console.log(certifications.getImgCert()['imgSrc']);
templateItem.find('.img-responsive').attr('src',certifications.getImgCert()['imgSrc']);
});
});//document.ready
And here all of the home page I'm working on:
http://codepen.io/abomaged/pen/JXMXzV
Thanks a lot

It's because your getNextCert function is returning an index that's outside the bounds of your certifications array. When nextCert is 1, the check to see if it's out of bounds of the array passes, so your code then increments nextCert to 2 and returns data[2] which is undefined. You need to change your getNextCert function:
getNextCert : function(){
this.nextCert += 1;
if(this.nextCert === this.data.length){
this.nextCert = 0;
}
return this.nextCert;
},

Related

Uncaught TypeError: Cannot read property 'contains' of null

I'm currently working on a project, where I'm using the following slider in the overal site:
S3Slider
For the particular page I'm currently working on I'm also making use of Walter Zorns' Drag&Drop image library. (Link Here)
Now when I start to make use of the SET_DHTML function, which is required for using the D&D library, my slider starts throwing errors:
Uncaught TypeError: Cannot read property 'contains' of null
The line number given, sends me to the following line:
if($(itemsSpan[currNo]).css('bottom') == 0) {
Which lies in the following piece of code:
s3Slider = function(id, vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 2000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderTopstory");
var itemsSpan = $("#sliderContent .sliderTopstory span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
/* This line -> */if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function( ) {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
Why is this error being thrown?
Thanks.
I think your problem lies in these two lines:
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
If jQuery doesn't find the item in the array, it's going to send you a value of -1 (on the top line) which will then be changed to 0 because you added 1. Now, if currNo is 0 on the second line, it's going to change it back to -1, which will return you undefined. Maybe try and change it to do this instead:
var currNo = jQuery.inArray(current, items);
if (currNo === items.length - 1) {
currNo = 0;
}
I'm not positive this is the problem, but I can see this becoming an issue if it's not the problem you're currently having.

$.fn.<new_function> 'is not a function' jQuery

EDIT: code link with better formatting:
EDIT: code updated with improvements from JSHint
http://pastebin.com/hkDQfZy1
I am trying to use $.fn to create a new function on jQuery objects by using it like:
$.fn.animateAuto = function(x,y) { }
And calling it by:
var card = $(id);
.....
var expanderButton = card.find(".dock-bottom");
.....
expanderButton.animateAuto('height', 500);
and I get:
Uncaught TypeError: expanderButton.animateAuto is not a function
What am I doing incorrectly? The $.cssHooks extension works just fine along with $.fx.
Here is the code:
var CSS_VIS = 'visibility'
var CSS_VIS_VIS = 'visible';
var CSS_VIS_HID = 'hidden';
var CSS_TEXTBOX_CONTAINER = ".text-box-container";
$.cssHooks['rotate'] = {
get: function (elem, computed, extra) {
var property = getTransformProperty(elem);
if (property) {
return elem.style[property].replace(/.*rotate\((.*)deg\).*/, '$1');
} else {
return '';
}
},
set: function (elem, value) {
var property = getTransformProperty(elem);
if (property) {
value = parseInt(value);
$(elem).data('rotatation', value);
if (value == 0) {
elem.style[property] = '';
} else {
elem.style[property] = 'rotate(' + value % 360 + 'deg)';
}
} else {
return '';
}
}
};
$.fn.animateAuto = function (prop, speed) {
return this.each(function (i, el) {
el = jQuery(el);
var element = el.clone().css({ 'height': 'auto' }).appendTo("body");
var height = element.css("height");
var width = element.css("width");
element.remove();
if (prop === "height") {
el.animate({ 'height': height }, speed);
} else if (prop = "width") {
el.animate({ 'width': width }, speed);
} else if (prop = "both") {
el.animate({ 'height': height, 'width:': width }, speed);
}
});
}
$.fx.step['rotate'] = function (fx) {
$.cssHooks['rotate'].set(fx.elem, fx.now);
};
function getTransformProperty(element) {
var properties = [
'transform',
'WebkitTransform',
'MozTransform',
'msTransform',
'OTransform'];
var p;
while (p = properties.shift()) {
if (element.style[p] !== undefined) {
return p;
}
}
return false;
}
function isExpanded(card) {
return card.find(CSS_TEXTBOX_CONTAINER).css(CSS_VIS) == CSS_VIS_VIS;
}
function expandCard(id) {
var card = $(id);
var isCardExpanded = isExpanded(card);
var expanderButton = card.find(".dock-bottom");
card.animate({
height: isCardExpanded ? '80px' : '270px'
}, 500);
var startValue = isCardExpanded ? 1 : 0;
var endValue = isCardExpanded ? 0 : 1;
var visibilityValue = isCardExpanded ? CSS_VIS_HID : CSS_VIS_VIS;
var textBoxes = card.find(CSS_TEXTBOX_CONTAINER);
textBoxes.fadeTo(0, startValue);
textBoxes.css(CSS_VIS, visibilityValue).fadeTo(500, endValue);
var topValue = isCardExpanded ? 'auto' : '200px';
if (isCardExpanded) {
expanderButton.animateAuto('height', 500);
} else {
expanderButton.animate({
top: '200px'
}, 500);
}
expanderButton.find("span").text(isCardExpanded ? "More Info" : "Less Info");
var buttonthing = expanderButton.find("button");
expanderButton.find("button").animate({ rotate: isCardExpanded ? 0 : -180 });
};
The issue is that jQuery was loaded multiple times. I am using ASP.NET MVC5 and was loading jQuery in the PartialView (re-usable UI control) and the main page which was causing my extension to be overriden.
I would post code but it would be too verbose and has nothing to do with jQuery or JavaScript. To solve though, all I did was remove the jQuery script import from the PartialView since jQuery is imported on every page by the master page.
Thanks everyone for helping out though, you all proved to me that this was not a simple problem that I was overthinking and that more research was necessary.

Type Error when using prototypes

I'm just getting started on Prototypes, and I'm trying to test different things on a website I'm developing. But I stumbled upon an error and I'm not sure why, because I was using that property before and it worked.
I ain't no experienced JavaScript developer, I'm still learning, but here's what I got:
var defaults = {
local_storage_key : "Cluster",
plugin_navigation : ".navigation",
plugin_wrapper : "content-wrapper",
iqns_class : ".iqn"
}
var Clusters = function(environment, options){
this.options = $.extend({}, defaults, options);
this.environment = environment;
this.viewport = $(window);
this.viewport_width = this.viewport.width();
this.viewport_height = this.viewport.height();
this.data_key = this.options.local_storage_key;
this.iqns_class = this.viewport.find(this.options.iqns_class);
this.iqn = this.iqns_class.parent();
this.shop_initiated = false;
this.plugin_navigation = this.options.plugin_navigation;
this.plugin_wrapper = this.options.plugin_wrapper;
this.initiate_plugin(this.plugin_navigation, {
containerID : this.plugin_wrapper,
first : false,
previous : false,
next : false,
last : false,
startPage : this.get_local_storage_data(),
perPage : 6,
midRange : 15,
startRange : 1,
endRange : 1,
keyBrowse : false,
scrollBrowse: false,
pause : 0,
clickStop : true,
delay : 50,
direction : "auto",
animation : "fadeInUp",
links : "title",
fallback : 1000,
minHeight : true,
callback : function(pages) {
this.set_local_storage_data(pages.current);
}
});
this.initiate_auxiliars();
this.set_environment();
};
Clusters.prototype.set_local_storage_data = function(data_val) {
return localStorage.setItem(this.data_key, data_val);
};
Clusters.prototype.get_local_storage_data = function() {
return +(localStorage.getItem(this.data_key) || 1);
};
Clusters.prototype.shop_iqns_selected_class = function() {
var self = this;
if (this.viewport_width < 980) {
$(this.iqns_class).each(function(index, element) {
var element = $(element);
$(self.iqn).on('click', function() {
if (element.hasClass('selected')) {
element.removeClass('selected');
} else {
element.addClass('selected');
}
});
});
}
}
Clusters.prototype.initiate_plugin = function(plugin_navigation, plugin_options) {
return $(plugin_navigation).jPages(plugin_options);
}
Clusters.prototype.initiate_auxiliars = function() {
return this.shop_iqns_selected_class();
}
Clusters.prototype.set_environment = function() {
if(this.environment == "Development") {
less.env = "development";
less.watch();
}
}
var cluster = new Clusters("Development");
I'm sure there's something I'm doing wrong or misunderstood about Prototyping, because otherwise I wouldn't get any errors. I'm just asking for some opinions or some directions on what I'm doing wrong, and what I should do or shouldn't do.
This is the error I get:
Uncaught TypeError: Object #<Object> has no method 'set_local_storage_data' on line 53
As you are using a callback function, the this keyword won't reference the cluster object any more. The callback will be executed in some other context, which "has no method 'set_local_storage_data'".
To avoid that, you can either bind() the function to your cluster object, or you use a local variable in the constructor's scope to reference the cluster object:
var that = this;
this.initiate_plugin(
...,
function(pages) {
that.set_local_storage_data(pages.current);
}
);

jQuery plugin activation bug

I'm having some trouble identifying a bug on the website I'm developing. To be more specific, I'm using jPages twice on the same page.
The first instance of the plugin is used as a navigation through the website as it is a one page website. A
nd the second instance is used to browse through a bunch of products rather than scrolling.
You can find the website I'm building here : .
I'll also paste all the JavaScript, because I have no idea for now where the bug is and why is behaving like that :
$(document).ready(function() {
var default_cluster_options = {
environment : "Development",
local_storage_key : "Cluster",
plugin_navigation_class : ".navigation",
plugin_wrapper_id : "content-wrapper",
headings : ['.heading-first h1', '.heading-second h1'],
input_types : ['input', 'textarea'],
info_iqns_class : ".iqn",
preview_iqn_class : ".preview",
limits : [ { min: 1224, items: 8 }, { min: 954, items: 6 }, { min: 624, items: 4 }, { min: 0, items: 2 } ],
shop_local_storage_key : "Shop",
};
var default_plugin_options = {
containerID : "",
first : false,
previous : false,
next : false,
last : false,
startPage : 1,
perPage : 1,
midRange : 6,
startRange : 1,
endRange : 1,
keyBrowse : false,
scrollBrowse: false,
pause : 0,
clickStop : true,
delay : 50,
direction : "auto",
animation : "fadeIn",
links : "title",
fallback : 1000,
minHeight : true,
callback : function(pages, items) {}
};
var Cluster = function(cluster_options, plugin_options) {
var self = this;
this.options = $.extend({}, default_cluster_options, cluster_options);
this.plugin_options = $.extend({}, default_plugin_options, plugin_options);
this.environment = this.options.environment;
this.data_key = this.options.local_storage_key;
this.shop_data_key = this.options.shop_local_storage_key;
this.plugin_navigation_class = this.options.plugin_navigation_class;
this.plugin_wrapper_id = this.options.plugin_wrapper_id;
this.headings = this.options.headings;
this.input_types = this.options.input_types;
this.viewport = $(window);
this.body = $('body');
this.viewport_width = this.viewport.width();
this.viewport_height = this.viewport.height();
this.info_iqns_class = this.body.find(this.options.info_iqns_class);
this.preview_iqn_class = this.body.find(this.options.preview_iqn_class);
this.limits = this.options.limits;
this.current_shop_page = this.options.current_shop_page;
this.total_shop_pages = this.options.total_shop_pages;
this.initiate_cluster(self.plugin_navigation_class, {
containerID : self.plugin_wrapper_id,
startPage : +(self.get_local_storage_data(self.data_key) || 1),
callback : function(pages){
self.set_local_storage_data(self.data_key, pages.current);
}
});
this.inititate_shop();
this.initiate_shop_touch_events();
};
Cluster.prototype.set_environment = function() {
if(this.environment == "Development") {
less.env = "development";
less.watch();
}
};
Cluster.prototype.set_local_storage_data = function(data_key, data_val) {
return localStorage.setItem(data_key, data_val);
};
Cluster.prototype.get_local_storage_data = function(data_key) {
return localStorage.getItem(data_key);
};
Cluster.prototype.initiate_scalable_text = function() {
for(var i in this.headings) {
$(this.headings[i]).fitText(1.6);
}
};
Cluster.prototype.initiate_placeholder_support = function() {
for(var i in this.input_types) {
$(this.input_types[i]).placeholder();
}
};
Cluster.prototype.initiate_iqn_selected_class = function() {
if(this.viewport_width < 980) {
$(this.info_iqns_class).each(function(index, element) {
var iqn = $(element).parent();
$(iqn).on('click', function() {
if($(iqn).hasClass('selected')) {
$(iqn).removeClass('selected');
} else {
$(iqn).addClass('selected');
}
});
});
}
};
Cluster.prototype.initiate_preview_action = function() {
$(this.preview_iqn_class).each(function(index, element) {
var data = $(element).attr('data-image-link');
$(element).on('click', function(ev) {
$.lightbox(data, {
'modal' : true,
'autoresize' : true
});
ev.preventDefault();
});
});
};
Cluster.prototype.initiate_plugin = function(plugin_navigation, plugin_options) {
var options = $.extend({}, this.plugin_options, plugin_options);
return $(plugin_navigation).jPages(options);
};
Cluster.prototype.initiate_shop_touch_events = function() {
var self = this;
return $("#shop-items-wrapper").hammer({prevent_default: true, drag_min_distance: Math.round(this.viewport_width * 0.1)}).bind("drag", function(ev) {
var data = JSON.parse(self.get_local_storage_data(self.shop_data_key));
if (ev.direction == "left") {
var next_page = parseInt(data.current_page + 1);
if(next_page > 0 && next_page <= data.total_pages) {
$(".shop-items-navigation").jPages(next_page);
}
}
if(ev.direction == "right") {
var prev_page = parseInt(data.current_page - 1);
if(prev_page > 0 && prev_page <= data.total_pages) {
$(".shop-items-navigation").jPages(prev_page);
}
}
});
}
Cluster.prototype.inititate_shop = function() {
var self = this;
for(var i = 0; i < this.limits.length; i++) {
if(this.viewport_width >= this.limits[i].min) {
this.initiate_plugin('.shop-items-navigation', {
containerID : "shop-items-wrapper",
perPage : self.limits[i].items,
midRange : 8,
animation : "fadeIn",
links : "blank",
keyBrowse : true,
callback : function(pages) {
var data = {
current_page : pages.current,
total_pages : pages.count
}
self.set_local_storage_data(self.shop_data_key, JSON.stringify(data));
}
});
return false;
}
}
};
Cluster.prototype.initiate_cluster = function(plugin_navigation, plugin_options) {
this.set_environment();
this.initiate_scalable_text();
this.initiate_placeholder_support();
this.initiate_iqn_selected_class();
this.initiate_preview_action();
this.initiate_plugin(plugin_navigation, plugin_options);
};
var cluster = new Cluster();
});
And the bug I was talking about, when you are on the Home page and navigate to the Shop page you will notice the the second instance of the plugin doesn't activate as the items should only be 8 ( if the width of the screen is more than 1224px ) and you should be able to browse through with the keyboard left and right arrows, but you cannot.
But if you are on the Shop page, hit refresh and the plugin will now activate after page load.
So, I would like some help with that, tracking the bug, because I'm still learning JavaScript and I'm not very experienced with it.
According to jPages source file this happens because at second plugin initialization plugin can't find :visible elements as they are hidden by first plugin initialization (line 60):
this._items = this._container.children(":visible");
To load your shop module with jPages plugin you need to initialize that plugin after shop items are shown. To do this you need to modify callback value in initiate_cluster function:
Lets say that Shop page index is 4:
Cluster.prototype.initiate_cluster = function(plugin_navigation, plugin_options) {
// ... your code
plugin_options.callback = function( pages ) {
if( pages.current == 4 ) {
this.inititate_shop();
}
};
this.initiate_plugin(plugin_navigation, plugin_options);
};
And remove this.inititate_shop(); function call from Cluster class constructor.
This should work.
Or you can try to swap plugin calls, but I'm not sure:
// first we initiate shop
this.inititate_shop();
// then main site navigation
this.initiate_cluster(self.plugin_navigation_class, {
containerID : self.plugin_wrapper_id,
startPage : +(self.get_local_storage_data(self.data_key) || 1),
callback : function(pages){
self.set_local_storage_data(self.data_key, pages.current);
}
});

$ is not a function errors

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

Categories