So I have this website where I load content from another .html in into a container using ajax. The problem that I have been facing is that the loaded content with a gallery that uses a script called "mosaic.js", isn't working. The weird thing is that the getScript does work for another script.
This is the script that I used for the content replacer.
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-load-in-and-animate-content-with-jquery/
$(document).ready(function() {
var hash = window.location.hash.substr(1); var href = $('#nav a').each(function(){ var href = $(this).attr('href'); if(hash==href.substr(0,href.length-4)){ var toLoad = hash+'.php #projectcontainer4'; $('#projectcontainer4').load(toLoad) } });
$('#nav a').live('click', function () {
var toLoad = $(this).attr('href')+' #projectcontainer4'; $('#projectcontainer4').hide('fast',loadContent); $('#load').remove(); $('#wrapper').append('LOADING...'); $('#load').fadeIn('normal'); window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
$('#projectcontainer4').empty();
function loadContent() { $('#projectcontainer4').load(toLoad,'',showNewContent) }
function showNewContent() { $.getScript("mosaic.js"); $('#projectcontainer4').show('normal',hideLoader()); }
function hideLoader() { $('#load').fadeOut('normal');
$('html, body').animate({scrollTop : 200},800);
}
return false;
});
});
This is the script that doesn't work in the loaded content
(function($){
if(!$.omr){
$.omr = new Object();
};
$.omr.mosaic = function(el, options){
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("omr.mosaic", base);
base.init = function(){
base.options = $.extend({},$.omr.mosaic.defaultOptions, options);
base.load_box();
};
// Preload Images
base.load_box = function(){
// Hide until window loaded, then fade in if (base.options.preload){
$(base.options.backdrop, base.el).hide();
$(base.options.overlay, base.el).hide();
$(window).load(function(){
// IE transparency fade fix
if(base.options.options.animation == 'fade' && $(base.options.overlay, base.el).css('opacity') == 0 ) $(base.options.overlay, base.el).css('filter', 'alpha(opacity=0)');
$(base.options.overlay, base.el).fadeIn(200, function(){
$(base.options.backdrop, base.el).fadeIn(200);
});
base.allow_hover();
}); }else{
$(base.options.backdrop, base.el).show();
$(base.options.overlay , base.el).show();
base.allow_hover(); }
};
// Initialize hover animations
base.allow_hover = function(){
// Select animation switch(base.options.animation){
// Handle fade animations
case 'fade':
$(base.el).hover(function () {
$(base.options.overlay, base.el).stop().fadeTo(base.options.speed, base.options.opacity);
},function () {
$(base.options.overlay, base.el).stop().fadeTo(base.options.speed, 0);
});
break;
// Handle slide animations
case 'slide':
// Grab default overlay x,y position
startX = $(base.options.overlay, base.el).css(base.options.anchor_x) != 'auto' ? $(base.options.overlay, base.el).css(base.options.anchor_x) : '0px';
startY = $(base.options.overlay, base.el).css(base.options.anchor_y) != 'auto' ? $(base.options.overlay, base.el).css(base.options.anchor_y) : '0px';;
var hoverState = {};
hoverState[base.options.anchor_x] = base.options.hover_x;
hoverState[base.options.anchor_y] = base.options.hover_y;
var endState = {};
endState[base.options.anchor_x] = startX;
endState[base.options.anchor_y] = startY;
$(base.el).hover(function () {
$(base.options.overlay, base.el).stop().animate(hoverState, base.options.speed);
},function () {
$(base.options.overlay, base.el).stop().animate(endState, base.options.speed);
});
break; };
};
// Make it go!
base.init();
};
$.omr.mosaic.defaultOptions = {
animation : 'fade',
speed : 150,
opacity : 1,
preload : 0,
anchor_x : 'left',
anchor_y : 'bottom',
hover_x : '0px',
hover_y : '67px',
overlay : '.mosaic-overlay', //Mosaic overlay backdrop : '.mosaic-backdrop' //Mosaic backdrop
};
$.fn.mosaic = function(options){
return this.each(function(){
(new $.omr.mosaic(this, options));
});
};
})(jQuery);
And this is the script that does actually work when I load it with the same method.
// JavaScript Document
$('.ppt li:gt(0)').hide(); $('.ppt li:last').addClass('last'); $('.ppt li:first').addClass('first'); $('#play').hide();
var cur = $('.ppt li:first'); var interval;
$('#fwd').click( function() { goFwd(); showPause(); } );
$('#back').click( function() { goBack(); showPause(); } );
function goFwd() { stop(); forward(); start(); }
function goBack() { stop(); back(); start(); }
function back() { cur.fadeOut( 500 ); if ( cur.attr('class') == 'first' ) cur = $('.ppt li:last'); else cur = cur.prev(); cur.fadeIn( 500 );}function forward() {cur.fadeOut( 500 );if ( cur.attr('class') == 'last' )cur = $('.ppt li:first');else cur = cur.next();cur.fadeIn( 500 );}function showPause() {$('#play').hide();$('#stop').show();}function showPlay() {$('#stop').hide();$('#play').show();}function stop() {clearInterval( interval );}$(function() {start();} );
Related
I am appending dynamic DOM elements (after Ajax calls to gather the data) as seen below. I have narrowed the code down to what I believe is most important:
<!-- SideMenu HTML -->
<div id="sidebar-menu">
<ul id="folders">
<!-- AJAX DATA POPULATES MENU HERE -->
<!-- HTML File calling JS function -->
<script>
$(document).ready(function() {
getParentFolders('parentFolderTitle');
});
</script>
// JS File function...
var parentFolders; // Values retrieved from AJAX calls
function buildFolderMenu(index) {
var markup = '<li class="has_sub">' +
'<a ... > parentFolders[index].Name + '</a>' +
'<ul ...>' +
'<li> SUB FOLDER TEST <li>' +
'</ul>' +
'</li>';
$(#folders').append(markup);
}
EDIT: My code is interacting with a 3rd party template, after reading the replies, I was able to track down the file which handles the 'click events'. However, based on my own code shown above, I am not sure how to adjust the template code to work with my dynamically appended DOM.
Here is the template code handling the click: (I can see the 'menuItemClick' function is where this is likely handled, but how do I apply the '.on('', function())' adjustments here, based on how this file is written?)
/**
* Theme: Adminto Admin Template
* Author: Coderthemes
* Module/App: Main Js
*/
!function($) {
"use strict";
var Sidemenu = function() {
this.$body = $("body"),
this.$openLeftBtn = $(".open-left"),
this.$menuItem = $("#sidebar-menu a")
};
Sidemenu.prototype.openLeftBar = function() {
$("#wrapper").toggleClass("enlarged");
$("#wrapper").addClass("forced");
if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")) {
$("body").removeClass("fixed-left").addClass("fixed-left-void");
} else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")) {
$("body").removeClass("fixed-left-void").addClass("fixed-left");
}
if($("#wrapper").hasClass("enlarged")) {
$(".left ul").removeAttr("style");
} else {
$(".subdrop").siblings("ul:first").show();
}
toggle_slimscroll(".slimscrollleft");
$("body").trigger("resize");
},
//menu item click
Sidemenu.prototype.menuItemClick = function(e) {
if(!$("#wrapper").hasClass("enlarged")){
if($(this).parent().hasClass("has_sub")) {
}
if(!$(this).hasClass("subdrop")) {
// hide any open menus and remove all other classes
$("ul",$(this).parents("ul:first")).slideUp(350);
$("a",$(this).parents("ul:first")).removeClass("subdrop");
$("#sidebar-menu .pull-right i").removeClass("md-remove").addClass("md-add");
// open our new menu and add the open class
$(this).next("ul").slideDown(350);
$(this).addClass("subdrop");
$(".pull-right i",$(this).parents(".has_sub:last")).removeClass("md-add").addClass("md-remove");
$(".pull-right i",$(this).siblings("ul")).removeClass("md-remove").addClass("md-add");
}else if($(this).hasClass("subdrop")) {
$(this).removeClass("subdrop");
$(this).next("ul").slideUp(350);
$(".pull-right i",$(this).parent()).removeClass("md-remove").addClass("md-add");
}
}
},
//init sidemenu
Sidemenu.prototype.init = function() {
var $this = this;
var ua = navigator.userAgent,
event = (ua.match(/iP/i)) ? "touchstart" : "click";
//bind on click
this.$openLeftBtn.on(event, function(e) {
e.stopPropagation();
$this.openLeftBar();
});
// LEFT SIDE MAIN NAVIGATION
$this.$menuItem.on(event, $this.menuItemClick);
// NAVIGATION HIGHLIGHT & OPEN PARENT
$("#sidebar-menu ul li.has_sub a.active").parents("li:last").children("a:first").addClass("active").trigger("click");
},
//init Sidemenu
$.Sidemenu = new Sidemenu, $.Sidemenu.Constructor = Sidemenu
}(window.jQuery),
function($) {
"use strict";
var FullScreen = function() {
this.$body = $("body"),
this.$fullscreenBtn = $("#btn-fullscreen")
};
//turn on full screen
// Thanks to http://davidwalsh.name/fullscreen
FullScreen.prototype.launchFullscreen = function(element) {
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
},
FullScreen.prototype.exitFullscreen = function() {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
},
//toggle screen
FullScreen.prototype.toggle_fullscreen = function() {
var $this = this;
var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
if(fullscreenEnabled) {
if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
$this.launchFullscreen(document.documentElement);
} else{
$this.exitFullscreen();
}
}
},
//init sidemenu
FullScreen.prototype.init = function() {
var $this = this;
//bind
$this.$fullscreenBtn.on('click', function() {
$this.toggle_fullscreen();
});
},
//init FullScreen
$.FullScreen = new FullScreen, $.FullScreen.Constructor = FullScreen
}(window.jQuery),
//main app module
function($) {
"use strict";
var App = function() {
this.VERSION = "1.5.0",
this.AUTHOR = "Coderthemes",
this.SUPPORT = "coderthemes#gmail.com",
this.pageScrollElement = "html, body",
this.$body = $("body")
};
//on doc load
App.prototype.onDocReady = function(e) {
FastClick.attach(document.body);
resizefunc.push("initscrolls");
resizefunc.push("changeptype");
$('.animate-number').each(function(){
$(this).animateNumbers($(this).attr("data-value"), true, parseInt($(this).attr("data-duration")));
});
//RUN RESIZE ITEMS
$(window).resize(debounce(resizeitems,100));
$("body").trigger("resize");
// right side-bar toggle
$('.right-bar-toggle').on('click', function(e){
$('#wrapper').toggleClass('right-bar-enabled');
});
},
//initilizing
App.prototype.init = function() {
var $this = this;
//document load initialization
$(document).ready($this.onDocReady);
//init side bar - left
$.Sidemenu.init();
//init fullscreen
$.FullScreen.init();
},
$.App = new App, $.App.Constructor = App
}(window.jQuery),
//initializing main application module
function($) {
"use strict";
$.App.init();
}(window.jQuery);
/* ------------ some utility functions ----------------------- */
//this full screen
var toggle_fullscreen = function () {
}
function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
var w,h,dw,dh;
var changeptype = function(){
w = $(window).width();
h = $(window).height();
dw = $(document).width();
dh = $(document).height();
if(jQuery.browser.mobile === true){
$("body").addClass("mobile").removeClass("fixed-left");
}
if(!$("#wrapper").hasClass("forced")){
if(w > 990){
$("body").removeClass("smallscreen").addClass("widescreen");
$("#wrapper").removeClass("enlarged");
}else{
$("body").removeClass("widescreen").addClass("smallscreen");
$("#wrapper").addClass("enlarged");
$(".left ul").removeAttr("style");
}
if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")){
$("body").removeClass("fixed-left").addClass("fixed-left-void");
}else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")){
$("body").removeClass("fixed-left-void").addClass("fixed-left");
}
}
toggle_slimscroll(".slimscrollleft");
}
var debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
}
function resizeitems(){
if($.isArray(resizefunc)){
for (i = 0; i < resizefunc.length; i++) {
window[resizefunc[i]]();
}
}
}
function initscrolls(){
if(jQuery.browser.mobile !== true){
//SLIM SCROLL
$('.slimscroller').slimscroll({
height: 'auto',
size: "7px"
});
$('.slimscrollleft').slimScroll({
height: 'auto',
position: 'right',
size: "7px",
color: '#828e94',
wheelStep: 5
});
}
}
function toggle_slimscroll(item){
if($("#wrapper").hasClass("enlarged")){
$(item).css("overflow","inherit").parent().css("overflow","inherit");
$(item). siblings(".slimScrollBar").css("visibility","hidden");
}else{
$(item).css("overflow","hidden").parent().css("overflow","hidden");
$(item). siblings(".slimScrollBar").css("visibility","visible");
}
}
// === following js will activate the menu in left side bar based on url ====
$(document).ready(function() {
$("#sidebar-menu a").each(function() {
var pageUrl = window.location.href.split(/[?#]/)[0];
if (this.href == pageUrl) {
$(this).addClass("active");
$(this).parent().addClass("active"); // add active to li of the current link
$(this).parent().parent().prev().addClass("active"); // add active class to an anchor
$(this).parent().parent().prev().click(); // click the item to make it drop
}
});
});
var resizefunc = [];
This could because of the redraw event not firing on the browser implicitly after your DOM manipulation. Refer this post on how to redraw so your generated DOM is refreshed on the UI
Force DOM redraw/refresh on Chrome/Mac
If this doesn't work please share your CSS and the before DOM and after DOM generation screenshot
I am trying to create a text rotator with a pause on 3 seconds in the end and then repeat. I have found a relevant script but have some problems with adding the pause in the end.
Codepen:
http://codepen.io/AmruthPillai/pen/axvqB/
Script:
(function($) {
$.fn.extend({
rotaterator: function(options) {
var defaults = {
fadeSpeed: 500,
pauseSpeed: 100,
child: null
};
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = $(this);
var items = $(obj.children(), obj);
items.each(function() {
$(this).hide();
})
if (!o.child) {
var next = $(obj).children(':first');
} else {
var next = o.child;
}
$(next).fadeIn(o.fadeSpeed, function() {
$(next).delay(o.pauseSpeed).fadeOut(o.fadeSpeed, function() {
var next = $(this).next();
if (next.length == 0) {
next = $(obj).children(':first');
}
$(obj).rotaterator({
child: next,
fadeSpeed: o.fadeSpeed,
pauseSpeed: o.pauseSpeed
});
})
});
});
}
});
})(jQuery);
$(document).ready(function() {
$('#rotate').rotaterator({
fadeSpeed: 0,
pauseSpeed: 100
});
});
the function already uses pauseSpeed to delay the fadeOut so I added the following:
var nextDelay = $(next).is(':last-child') ? o.pauseSpeed + 3000 : o.pauseSpeed
I check if the next element .is(':last-child') and add 3000 to the value o.pauseSpeed
and used nextDelay instead of o.pauseSpeed to delay the fadeOut
Working CodePen
(function($) {
$.fn.extend({
rotaterator: function(options) {
var defaults = {
fadeSpeed: 500,
pauseSpeed: 100,
child: null
};
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = $(this);
var items = $(obj.children(), obj);
items.each(function() {
$(this).hide();
})
if (!o.child) {
var next = $(obj).children(':first');
} else {
var next = o.child;
}
$(next).fadeIn(o.fadeSpeed, function() {
var nextDelay = $(next).is(':last-child') ? o.pauseSpeed + 3000 : o.pauseSpeed
$(next).delay(nextDelay).fadeOut(o.fadeSpeed, function() {
var next = $(this).next();
if (next.length == 0) {
next = $(obj).children(':first');
}
$(obj).rotaterator({child: next,fadeSpeed: o.fadeSpeed,pauseSpeed: o.pauseSpeed});
})
});
});
}
});
})(jQuery);
$(document).ready(function() {
$('#rotate').rotaterator({
fadeSpeed: 500,
pauseSpeed: 100
});
});
related code is this:
$(next).delay(o.pauseSpeed).fadeOut(o.fadeSpeed, function() {
I changed it to this:
var nextDelay = $(next).is(':last-child') ? o.pauseSpeed + 3000 : o.pauseSpeed
$(next).delay(nextDelay).fadeOut(o.fadeSpeed, function() {
$(next): is the next element selector.
.is(':last-child'): checks if $(next) element is the last-child of their parent
.delay(number of milliseconds): .delay() Set a timer to delay execution of subsequent items in the queue (fadeOut in this case).
.fadeOut(): Hide the matched elements by fading them to transparent.
var nextDelay: is defined using Conditional (ternary) Operator
You can wait for 3 seconds or whatever interval you like using setTimeout call. I've updated your code. Check http://codepen.io/anon/pen/XMJQYy
if (next.length == 0){
next = $(obj).children(':first');
setTimeout(function() {
$(obj).rotaterator({child : next, fadeSpeed : o.fadeSpeed, pauseSpeed : o.pauseSpeed});
}, 2000);
} else {
$(obj).rotaterator({child : next, fadeSpeed : o.fadeSpeed, pauseSpeed : o.pauseSpeed});
}
I'm getting a console error (Uncaught TypeError: undefined is not a function) on line 156 on load and I can't figure it out for the life of me. I've provided the line in question and the full context its in below. Also, I added the site link in case it helps. I would appreciate any and all help/advice.
Site link
Here is the line in question (156): if (!$imgs.length) {return $.Deferred.resolve().promise();}
Here is the full code: http://pastebin.com/Ext4TwdP#
//*********************************************************
// Let's start, shall we?
//*********************************************************
jQuery(document).ready(function($) {
//*********************************************************
// Global variables
//*********************************************************
// Morphing icons
var myIcons = new SVGMorpheus('#iconset', {
duration: 250,
rotation: 'none'
});
//*********************************************************
// Turn off all Ajax caching (IE caches $.load)
//*********************************************************
$.ajaxSetup({
cache: false
});
//*********************************************************
// Preloader
//*********************************************************
window.addEventListener('DOMContentLoaded', function() {
$('#projects-list, footer p').hide();
new QueryLoader2(document.querySelector("body"), {
barColor: "#f30",
backgroundColor: "#000",
barHeight: 1,
minimumTime: 200,
fadeOutTime: 0,
onComplete: function() {
$('.site-overlay').remove();
$('#masthead').slideDown(100, function(){
$('#projects-list, footer p').show().addClass('fadeInUp');
});
// Set a timeout because 100ms is too quick
$(function() {
setTimeout(function() {
$('#projects-list, footer p').removeClass('fadeInUp');
}, 500);
});
}
});
});
//*********************************************************
// Small features
//*********************************************************
// Set top margin for #content to always match the height of the top header
function resize() {
var headerTop = $('#masthead').outerHeight();
(headerTop != parseInt($('#content').css('margin-top').slice(0, -2))) ? $('#content').stop().animate({'margin-top': headerTop}, 150) : console.log('');
}
resize();
window.onresize = resize;
// Hide header when scrolling down and show header when scrolling up
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st < lastScrollTop || st === 0){
$('#masthead').removeClass('unpinned');
} else {
$('#masthead').addClass('unpinned');
}
lastScrollTop = st;
});
//*********************************************************
// Project hovers
//*********************************************************
$('#content').on('mouseenter', 'article.project', function(){
// If loading icon doesn't exist in the DOM...
if ( !$('.overlay').find('.loading-icon').length) {
// And if the project wrapper is activated...
if ( $(this).closest('#main').find('#project-wrapper').hasClass('activated') ) {
$(this).addClass('hover');
} else {
$(this).addClass('hover grayscale grayscale-fade');
}
// If loading icon exists in the DOM...
} else {
$(this).find('.post-link').hide();
}
// Dirty fix for 1px white flicker on hover (Chrome)
var overlayWidth = $('article.project').outerWidth();
$('.overlay').css({
marginLeft: -1,
width: overlayWidth + 2
});
}).on('mouseleave', 'article.project', function(){
// If #project-wrapper is activated...
if ( $(this).closest('#main').find('#project-wrapper').hasClass('activated') ) {
$(this).removeClass('hover');
$(this).find('.post-link').show();
// If #project-wrapper is not activated...
} else {
// If loading icon is present...
if ( $(this).find('.loading-icon').length ) {
// Only remove the 'hover' class
$(this).removeClass('hover');
// If loading icon is not present...
} else {
// Remove all classes
$(this).removeClass('hover grayscale grayscale-fade');
$(this).find('.post-link').show();
}
}
});
// Adjust the project titles so they always fit the container nicely
function adjustTitle() {
var thumbWidth = $('article.project > img').outerWidth();
if (thumbWidth <= 220) {
$('.overlay > h3').addClass('mobile');
} else {
$('.overlay > h3').removeClass('mobile');
}
}
$(window).on('resize', adjustTitle);
//*********************************************************
// Projects
//*********************************************************
(function($) {
// Function to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred.resolve().promise();}
// for each image, add a deferred object to the array which resolves when the image is loaded
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($,dfds);
}
// Function for additional styling
function projectStyles() {
// Check the first slide input
$('#slider input:first').attr('checked', 'checked');
$('#project-wrapper').addClass('activated');
// Make the articles grey again after activation
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
// CSS effects
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeInDown');
// Remove pesky, sticky 'hover' class
$('article.project').removeClass('hover');
}
// Open the project container
function openProject() {
var post_id = $(this).data('id'), // data-id attribute for .post-link
ajaxURL = site.custom_ajax; // Ajax URL localized from functions.php
// Add a loading icon
$('<span class="loading-icon"></span>').insertBefore(this);
// Add the 'active' class to make sure the div stays dark while loading
$(this).closest('article.project').addClass('active');
// Make all the articles grey when an article is clicked
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
// Remove the corner ribbon
$('article').removeClass('current');
$('.corner-ribbon').remove();
// Get the response from the Ajax function
$.ajax({
type: 'POST',
url: ajaxURL,
context: this,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
// Add a corner ribbon to note the current activated project
$(this).closest('article.project').removeClass('active').addClass('current');
$('<div class="corner-ribbon">Current</div>').prependTo('article.current');
// Wait until all images are loaded
$('#project-container').html(response).imagesLoaded().then(function() {
// Remove the loading icon
$('.loading-icon').remove();
// If the user has scrolled...
if ($(window).scrollTop() !== 0) {
// First scroll the page to the top
$('html, body').animate({
scrollTop : 0
},400, function() {
// Make the max-height of the container exact for a smoother transition
function matchContainerHeight() {
var containerHeight = $('#project-container').outerHeight();
$('#project-wrapper.activated').css('max-height', containerHeight);
}
setTimeout(matchContainerHeight, 100);
$(window).on('resize', matchContainerHeight);
projectStyles();
});
// If the user has not scrolled...
} else {
// Make the max-height of the container exact for a smoother transition
function matchContainerHeight() {
var containerHeight = $('#project-container').outerHeight();
$('#project-wrapper.activated').css('max-height', containerHeight);
}
setTimeout(matchContainerHeight, 100);
$(window).on('resize', matchContainerHeight);
projectStyles();
}
return false;
});
}
});
}
// User event
$('#content').on('click', '.post-link', function(e) {
e.preventDefault();
var projectTitle = $(this).data('title'), // data-title attribute for .post-link
projectSlug = $(this).data('slug') // data-slug attribute for .post-link
// Calls openProject() in context of 'this' (.post-link)
openProject.call(this);
$('head').find('title').text(projectTitle + ' | Keebs');
});
})(jQuery);
//*********************************************************
// Close button
//*********************************************************
(function($) {
// Close the project container
function closeProject() {
// Remove classes
$(this).removeClass('fadeInDown');
$('#project-wrapper').removeClass('activated').css('max-height', '');
$('article.project').removeClass('grayscale grayscale-fade').css('opacity', '1');
$('.post-container').removeClass('fadeInUp');
$('article').removeClass('current');
// Remove the corner ribbon since no projects are currently activated
$('.corner-ribbon').remove();
// Set the height of the project wrapper back to 0
$('body.single #project-wrapper').css('max-height', 0);
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#content').on('click', '.close-button', function(e) {
e.preventDefault();
closeProject();
});
})(jQuery);
//*********************************************************
// Home button
//*********************************************************
(function($) {
// Load the Home page
function loadHome() {
var contactButton = $('#contact-button');
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
$('body.single #project-wrapper').css('max-height', 0);
});
// Change the Projects button to 'Contact'
if ($('body').hasClass('contact')) {
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
}
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('.site-title a').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
loadHome();
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked')
}, 1000);
}
});
})(jQuery);
//*********************************************************
// Contact button
//*********************************************************
(function($) {
var contactButton = $('#contact-button');
// Load the Contact page
function loadContact() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
});
// Change the Contact button to 'Projects'
$(contactButton).removeClass('contact-button').addClass('project-button').attr('data-title', 'Projects').css('width', '71px').text('Projects').shuffleLetters();
myIcons.to('work');
// Change the title of the document
$('head').find('title').text('Contact | Keebs');
}
// Load the Projects page
function loadProjects() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
$('body.single #project-wrapper').css('max-height', 0);
});
// Change the Projects button to 'Contact'
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
if (!contactButton.hasClass('project-button')) {
loadContact();
} else {
loadProjects();
}
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked')
}, 500);
}
});
})(jQuery);
//*********************************************************
// Single template
//*********************************************************
// Check the first slide input
$('body.single #slider input:first').attr('checked', 'checked');
// Set the height of the project container
$('body.single #project-container').imagesLoaded().then(function() {
var containerHeight = $('#project-container').outerHeight();
$('body.single #project-wrapper').css('max-height', containerHeight);
});
// Make the projects list grayscale if the project wrapper is activated
if ( $('body.single #project-wrapper').hasClass('activated') ) {
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
}
//*********************************************************
// Shuffle Letters by Martin Angelov
//*********************************************************
(function($){
$.fn.shuffleLetters = function(prop){
var options = $.extend({
"step" : 8, // How many times should the letters be changed
"fps" : 60, // Frames Per Second
"text" : "", // Use this text instead of the contents
"callback" : function(){} // Run once the animation is complete
},prop)
return this.each(function(){
var el = $(this),
str = "";
// Preventing parallel animations using a flag;
if(el.data('animated')){
return true;
}
el.data('animated',true);
if(options.text) {
str = options.text.split('');
}
else {
str = el.text().split('');
}
// The types array holds the type for each character;
// Letters holds the positions of non-space characters;
var types = [],
letters = [];
// Looping through all the chars of the string
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
el.html("");
// Self executing named function expression:
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
// The animation is complete. Updating the
// flag and triggering the callback;
el.data('animated',false);
options.callback(el);
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at thsi position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
el.text(strCopy.join(""));
setTimeout(function(){
shuffle(start+1);
},1000/options.fps);
})(-options.step);
});
};
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
})(jQuery);
//*********************************************************
// iPad fix for slider
//*********************************************************
var iPadLabels = function () {
function fix() {
var labels = document.getElementsByTagName('label'),
target_id,
el;
for (var i = 0; labels[i]; i++) {
if (labels[i].getAttribute('for')) {
labels[i].onclick = labelClick;
}
}
}
function labelClick() {
el = document.getElementById(this.getAttribute('for'));
if (['radio', 'checkbox'].indexOf(el.getAttribute('type')) != -1) {
el.setAttribute('selected', !el.getAttribute('selected'));
} else {
el.focus();
}
}
return {
fix: fix
}
}();
window.onload = function () {
iPadLabels.fix();
}
//*********************************************************
// Annnd, we're done!
//*********************************************************
});
There were a couple problems with this.
1) I didn't declare the imgs variable.
2) I didn't include the () after $.Deferred.
So here's the updated code block:
// Function to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {
var imgs = this.find('img[src!=""]');
// If there are no images, just return an already resolved promise
if (!imgs.length) {
return $.Deferred().resolve().promise();
}
// For each image, add a deferred object to the array which resolves when the image is loaded
var dfds = [];
imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();};
img.src = this.src;
});
// Return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($, dfds);
};
My website uses onePageNav and scrollTo jquery code. I would like to insert code which correct my position on the website when i click on the same link in the navigation (i scroll mouse up or down but current button (hover) in navigation has not moved yet on to the next one).
OnePageNav code:
;
(function ($, window, document, undefined) {
// our plugin constructor
var OnePageNav = function (elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$nav = this.$elem.find('a');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
currentClass: 'current',
changeHash: true,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollOffset: 0,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function () {
var self = this;
// Introduce defaults that can be extended either
// globally or using an object literal.
self.config = $.extend({}, self.defaults, self.options, self.metadata);
//Filter any links out of the nav
if (self.config.filter !== '') {
self.$nav = self.$nav.filter(self.config.filter);
}
//Handle clicks on the nav
self.$nav.on('click.onePageNav', $.proxy(self.handleClick, self));
//Get the section positions
self.getPositions();
//Handle scroll changes
self.bindInterval();
//Update the positions on resize too
self.$win.on('resize.onePageNav', $.proxy(self.getPositions, self));
return this;
},
adjustNav: function (self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function () {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function () {
self.didScroll = true;
});
self.t = setInterval(function () {
docHeight = self.$doc.height();
//If it was scrolled
if (self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if (docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function ($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function () {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function () {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if ($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos) - self.config.scrollOffset;
}
});
},
getSection: function (windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for (var section in this.sections) {
if ((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function (e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if (!$parent.hasClass(self.config.currentClass)) {
//Start callback
if (self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
$.scrollTo(newLoc, self.config.scrollSpeed, {
axis: 'y',
easing: self.config.easing,
offset: {
top: -self.config.scrollOffset
},
onAfter: function () {
//Do we need to change the hash?
if (self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if (self.config.end) {
self.config.end();
}
}
});
}
e.preventDefault();
},
scrollChange: function () {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if (position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if (!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if (this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
unbindInterval: function () {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function (options) {
return this.each(function () {
new OnePageNav(this, options).init();
});
};
})(jQuery, window, document);
$(function () { // this is the shorthand for document.ready
$(window).scroll(function () { // this is the scroll event for the document
scrolltop = $(window).scrollTop(); // by this we get the value of the scrolltop ie how much scroll has been don by user
if (parseInt(scrolltop) >= 80) // check if the scroll value is equal to the top of navigation
{
$("#navbar").css({
"position": "fixed",
"top": "0"
}); // is yes then make the position fixed to top 0
} else {
$("#navbar").css({
"position": "absolute",
"top": "80px"
}); // if no then make the position to absolute and set it to 80
}
}); //here
}); //here
I'm trying to add an image rotator to my site but for some reason firebug tells me the function I need to call to start the rotator isn't defined. My jQuery file is loading just fine and the image rotator script is loading so I'm not sure what is wrong. The site is heritage.newcoastmedia.com but I'll go ahead and post the script:
;(function($) {
$.fn.featureList = function(options) {
var tabs = $(this);
var output = $(options.output);
new jQuery.featureList(tabs, output, options);
return this;
};
$.featureList = function(tabs, output, options) {
function slide(nr) {
if (typeof nr == "undefined") {
nr = visible_item + 1;
nr = nr >= total_items ? 0 : nr;
}
tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');
output.stop(true, true).filter(":visible").fadeOut();
output.filter(":eq(" + nr + ")").fadeIn(function() {
visible_item = nr;
});
}
var options = options || {};
var total_items = tabs.length;
var visible_item = options.start_item || 0;
options.pause_on_hover = options.pause_on_hover || true;
options.transition_interval = options.transition_interval || 5000;
output.hide().eq( visible_item ).show();
tabs.eq( visible_item ).addClass('current');
tabs.click(function() {
if ($(this).hasClass('current')) {
return false;
}
slide( tabs.index( this) );
});
if (options.transition_interval > 0) {
var timer = setInterval(function () {
slide();
}, options.transition_interval);
if (options.pause_on_hover) {
tabs.mouseenter(function() {
clearInterval( timer );
}).mouseleave(function() {
clearInterval( timer );
timer = setInterval(function () {
slide();
}, options.transition_interval);
});
}
}
};
});
And here is the script to start the image rotator:
<script language="javascript">
$(document).ready(function() {
$.featureList(
$("#tabs li a"),
$("#output li"), {
start_item : 1
}
);
});
</script>
Your code creates an anonymous function, but doesn't call it.
You need to call the function by adding (jQuery) at the end.
You cannot do $.featureList(
See Chrome error:
The plugin needs to applied to an object
You've just slightly missed out on the right syntax for creating a plugin. What you really want is:
(function($) {
$.fn.featureList = function() { // etc; }
$.featureList = function() { // yet more etc; }
})(jQuery);