I’ve got a situation, that I’m pretty sure is something basic, that I just don’t know the proper syntax/sequence for:
I’ve got the following code in my site’s $(document).ready(function():
$(document).ready(function() {
//Prevents default anchor tag behavior
$('#socialScroller a, #contributePod a, .prev, .next').click(function(e) {
e.preventDefault();
});
//Scrollable for Social Sidebar area
$(".socialScrollable").scrollable({ easing:"easeInOutCubic", vertical:true, next:".socialNext", prev:".socialPrev"});
var scrollable = jQuery(".socialScrollable").data("scrollable");
var size = 3;
scrollable.onSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
jQuery("a.socialNext").addClass("disabled");
}
});
scrollable.onBeforeSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
if (index > this.getIndex()) {
return false;
}
}
});
//Scrollable for History page
$(".historyScrollable").scrollable({ easing:"easeInOutCubic"}).navigator();
//Scrollables for Media page
$(".mediaScrollable").scrollable({ easing:"easeInOutCubic"}).navigator({navi:'#pressNavTabs'});
$("#mediaNavScrollable").scrollable({ easing:"easeInOutCubic", next:".nextMedia", prev:".prevMedia"});
var scrollable = jQuery("#mediaNavScrollable").data("scrollable");
var size = 4;
scrollable.onSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
jQuery("a.nextMedia").addClass("disabled");
}
});
scrollable.onBeforeSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
if (index > this.getIndex()) {
return false;
}
}
});
$("#mediaNavScrollable").scrollable({ easing:"easeInOutCubic"});
//History Scroller
$(function() {
$(".vertHistoryScroller").scrollable({ vertical:"true", easing:"easeInOutCubic", next:".nextVert", prev:".prevVert" }).navigator();
});
//Contribute Sidebar Actions
$(".contributeContainer").hide();
$("#contributePod a").click(function(){
var aData = $(this).attr("data-name");
$(".contributeContainer").fadeOut("fast");
$("#"+aData).fadeIn("slow");
});
$(".contributeContainer a").click(function(){
$(this).parent(".contributeContainer").fadeOut("fast");
});
});
On any page that does not have #mediaNavScrollable, I get this error in the JS console:
Uncaught TypeError: Cannot call method ‘onSeek’ of undefined.
If I comment everything from the “var scrollable” line down, everything works fine on pages without that #mediaNavScrollable ID. How do I wrap that JS so that it only fires if it has #mediaNavScrollable?
You need to check to see if
scrollableis not null and has any elements in it. If it doesnt, exit the handler.This will exit the handler without running any other code. Alternately, you can use an if block: