I have this code
$(document).ready(function(){
var fade_in = function(){
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
});
What it does is that the div "quote" slowly fades in, stays for a few seconds and then fades out. What I want is that all this happens when the user is on the page, if you're not in the page,the text fades in, fades out and you miss it. How can I do that?
There are two ways
First : (bit old)
$(document).ready(function() {
window.onfocus = function() {
var fade_in = function() {
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
};
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">quote</div>
Second :
function getHiddenProp() {
var prefixes = ['webkit', 'moz', 'ms', 'o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++) {
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
document.addEventListener(evtname, visChange);
}
function visChange() {
var txtFld = document.getElementById('visChangeText');
if (txtFld) {
if (!isHidden()) {
var fade_in = function() {
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
};
}
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">quote</div>
This will execute when page div visible
$(document).ready(function(){
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
});
Related
How I am supposed to combine the below ones into one single working script?
When is clicked once a color picked-up by user appears,click again the color turns in white and when double-clicked appears aqua. It is too long code, I tried to combine them, but I made mistake.
//single click
$('#pixel_canvas').on('click', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'white');
}
});
//double click
$('#pixel_canvas').on('dblclick', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'aqua');
}
});
I'd go something like this:
// Take your actual 'core' code and turn it into a jQuery function:
$.fn.setColor(colorOff){
if( $(this).hasClass("blank") ){
$(this)
.css('background-color', $('#colorPicker').val())
.removeClass('blank');
} else{
$(this)
.addClass('blank')
.css('background-color',colorOff);
}
}
// Now bind the events to the element and pass the color needed for the events:
$('#pixel_canvas')
.on('click','td',function(){
$(this).setColor('white')
})
.on('dblclick','td',function(){
$(this).setColor('aqua')
});
This may help.
function doClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','white');
}
}
function doDoubleClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','aqua');
}
}
var timer = 0;
var delay = 200;
var prevent = false;
$("#pixel_canvas")
.on("click", function() {
timer = setTimeout(function() {
if (!prevent) {
doClickAction();
}
prevent = false;
}, delay);
})
.on("dblclick", function() {
clearTimeout(timer);
prevent = true;
doDoubleClickAction();
});
I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>
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);
};
I am trying to develope a slider, which change every 5 seconds if the user doens´t hit the back- or forward-button.
But if he (the user) does, the interval fires multiple times... why?
I save the Interval in a variable and clear this variable so i don´t know why this dont work... but see yourself:
jQuery.fn.extend({
wrGallery: function() {
return this.each(function() {
// config
var wrClassActive = 'galerie_active';
var wrTime = 5000;
// wrAutomaticDirection gibt an, in welche Richtung
// die Gallerie bei automatischem Wechsel wechseln soll (True = vorwärts/rechts)
var wrAutomaticDirection = true;
var wr = jQuery(this);
var wrGalleryContents = wr.find('.galerie_content');
var wrGalleryContentsFirst = wr.find('.galerie_content:first-child');
var wrBtnBack = wr.find('#galerie_backward');
var wrBtnFor = wr.find('#galerie_forward');
var wrTimer = 0;
var wrI = 0;
var wrOldActiveID = 0;
var wrInit = function() {
wrGalleryContents.each(function() {
wrI++;
jQuery(this).attr('id', wrI);
jQuery(this).css({
display: 'none',
opacity: 0
})
})
wrGalleryContentsFirst.css({
display: 'block',
opacity: 1
})
wrGalleryContentsFirst.addClass('galerie_active')
wrStartTimer();
}
var wrStartTimer = function() {
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
}
var wrStoppTimer = function() {
clearInterval(wrTimer);
wrTimer = 0;
}
var wrBackground = function(wrDirection) {
wrOldActiveID = wr.find('.' + wrClassActive).attr('id');
wr.find('.' + wrClassActive).removeClass(wrClassActive);
if (wrDirection) {
wrOldActiveID++;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#1').addClass(wrClassActive);
}
} else {
wrOldActiveID--;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#3').addClass(wrClassActive);
}
}
}
var wrAnimate = function(wrDirection) {
wrGalleryContents.stop().animate({
opacity: 0
}, 500);
wr.find('.' + wrClassActive).css({
display: 'block'
})
wr.find('.' + wrClassActive).stop().animate({
opacity: 1
}, 500);
}
var wrChange = function(wrDirection) {
wrBackground(wrDirection);
wrAnimate(wrDirection);
}
wr.on('mouseenter', function() {
wrStoppTimer();
});
wr.on('mouseleave', function() {
wrStartTimer();
});
wrBtnBack.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(false);
});
wrBtnFor.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(true);
});
wrInit();
});
}
});
Thanks for reading ;-)
Add a wrStoppTimer() call at the beginning of wrStartTimer:
var wrStartTimer = function() {
wrStoppTimer();
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
};
Also in the two click functions you have:
wrStoppTimer();
wrStartTimer();
you can remove that wrStoppTimer() call since wrStartTimer() will call it for you now.
One other thing: if you define functions the way you're doing with var name = function() { ... } you should put a semicolon after the closing } as in the updated code above.
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);