Writing and compiling a simple jQuery plugin - javascript

I am trying to compile a basic jQuery plugin which shows a div upon provided options when invoking:
select if a checkbox should be checked after X milliseconds or after X px on scroll,
if one of those two options are selected, set a delay value or scroll distance in px
otherwise do nothing
Example of desired options invoke:
$(document).ready( function() {
$('#testInput').testing({
myMethod : delay,
myValue : 2000
});
});
My current progress here: JSFiddle (it's not much as currently I'm still at a beginning of the learning curve)

After some fiddling i managed to get this working (kinda). Plugin seems to be working fine. Except there is some bug with the scroll function which i have to sort it out additionaly - it loops and changes checkbox states indefinitely instead just once.
Here is a working fiddle
And modified code:
(function($) {
$.fn.testing = function( options ) {
// Settings
var settings = $.extend({
delay : null,
delayTime : null,
scrolling : null,
scrollDist : null
}, options);
return this.each( function() {
var self = this;
// Timeout
setTimeout(function (){
$(self).prop('checked', settings.delay);
}, settings.delayTime);
// Scroll
if ($(window).scrollTop() > settings.scrollDist) {
$(this).prop('checked', settings.scrolling);
};
});
}
}(jQuery));
// Plugin invoke
$(window).on("load resize scroll",function(){
$('#testInput').testing({
delay : false,
delayTime : null,
scrolling : true,
scrollDist : 20,
});
});

Related

Problems with mouseover and mouseout events in a continuous jQuery content slider

I have tried to built a continuous content slider in jQuery.
If you don't hover over it, then it works fine, it slides (even though I feel like I made it happen in a wrong way).
When you hover it then it stops, but only for 2 seconds. As you'd imagine, it should stay stopped until the cursor is removed. Maybe the interval is not cleared properly?
Generally the whole thing works improperly when you starts to hover/unhover.
Here's a demo of my plugin: http://jsfiddle.net/T5Gt3/
(function ($) {
$.fn.productSlider = function(options) {
var defaults = {
speed: 2000
};
var config = $.extend(defaults, options);
this.each(function() {
var $this = $(this),
$scrollable = $this.find('#content-product-slider-inner'),
timeLeft;
function animateScrollable() {
$scrollable.animate({ left: '-120px' }, config.speed, 'linear', function() {
$scrollable.css({ left: '0px' }).find('a:first-child').remove().appendTo($scrollable);
});
};
animateScrollable();
var timer = setInterval(animateScrollable, config.speed);
$scrollable.mouseover(function() {
$scrollable.stop();
clearInterval(timer);
});
$scrollable.mouseout(function() {
animateScrollable();
var timer = setInterval(animateScrollable, config.speed);
});
});
return this;
};
})(jQuery);
Any help would be greatly appreciated.
$(".event_list_inner_wrapper").live({
mouseenter: function () {
$(this).find('.front_side').fadeOut(600).hide();
$(this).find('.back_side').fadeIn(600).show();
},
mouseleave: function () {
$(this).find('.back_side').fadeOut(600).hide();
$(this).find('.front_side').fadeIn(600).show();
}
});
That's code I used for a project that was similar to your description. Basically, bind the mice events, and do your thing.

Submenu animation "pops up"

I have a menu with sub items inside it. In order to make animation effect I want, I need to retrieve sub-menu width,height and height of its first-child. Now my animation works ,but sometimes my sub-menu just "pops up" (it doesn't animate its width ).
Here is The Fiddle of the problem.
http://www.vasinternetposao.com/wordpressdevelopment/wp-content/themes/override/images/submenu_problem.png
I am using this code:
var j = jQuery.noConflict();
j(document).ready(function () {
j('ul.nav').removeClass('nav').addClass('jnav'); //Add jquery Class to our menu
j('ul.jnav li').hover(function () {
if (j(this).children('ul:first').hasClass('jsub-menu')) { //Let's check if "jsub-menu" Class is here
return false; //If it is ("jsub-menu" here) don't SlideDown...
} else { //Else slide down if no class
j(this).find('ul.sub-menu:first').not(':animated').slideDown(500);
}
}, function () {
j(this).find('ul:first').slideUp(500, function () {
j(this).removeClass('jsub-menu').addClass('sub-menu');
j(this).css({
'height': '',
'width': ''
});
});
});
j('ul.jnav ul.sub-menu a').hover(function () {
j(this).addClass('active');
if (j('.active').next('ul.sub-menu').length) { //If submenu exist...
j('.active').next('ul.sub-menu').css({
'visibility': 'hidden',
'opacity': '0',
'display': 'block'
}); //Show it so we can read its:
var get_width = j('.active').next('ul.sub-menu').outerWidth(true); //WIDTH
var get_height_of_first_child = j('.active').next('ul.sub-menu').children('li:first').outerHeight(true); //HEIGHT of its First Child
var get_submenu_height = j('.active').next('ul.sub-menu').outerHeight(true); //HEIGHT of our menu
j('.active').next('ul').removeClass('sub-menu') //Remove class from menu, add another class apply HEIGHT of FIRST CHILD and hide it again...
.addClass('jsub-menu').css({
'visibility': '',
'opacity': '',
'height': get_height_of_first_child + 'px',
'width': '0'
});
j('.active').next('.jsub-menu').animate({
width: get_width
}, 1000, function () { //Animate WIDTH
j('.active').next('.jsub-menu').animate({
height: get_submenu_height
}, 1000); //callback animate HEIGHT
});
} //End if
}, function () {
j('.active').removeClass('active');
});
});
I think that this is happening because my Slide Up/Down animations are conflicting with my animate with/height functions but I am not sure. I have tried to solve it by adding stop(),stop(true,true),stop(true,false) in numerous combinations but failed. I am trying to solve this for days now so you stackers are my only hope. Please help!
Thank you!!
I was finally able to replicate the error.
I wrote this code for you, to replace the code you have for the animation.
var animating = false;
function animate($elm, options, callback) {
if (animating)
return;
animating = true;
$elm.animate(options, 1000, function() {
animating = false;
if (callback != undefined)
callback();
});
}
Call it like this, from inside your hover callback.
animate(j('.active').next('.jsub-menu'),
{
'width': get_width,
'height' : get_submenu_height
});
Basically, it checks if another animation is already running, in which case it doesn't start it. The Flag is set to false when the animation stopped, and let's other animations go on.
You can also pass a callback to do something after the animation is completed, but in your case you don't need it, because you can animate the height and width in the same time.
I tested it for like a minute and it looked pretty smooth.
Here is the updated feedle: http://jsfiddle.net/gabrielcatalin/TNxJ4/1/
P.S. You may also want to use the $ sign instead of 'j' for jQuery wrappers.

Unslider on Image Hover

I am using unslider, jquery light slider in my website which is working but can I keep the plugin in my image hover ?
I have tried these but doesnot work:
$(function() {
$('.banner').unslider({
autoplay:false;
});
});
$("#banner").hover(function(){
if($('#banner').autoplay('false')){
autoplay : true;
}, function (){
autoplay: false;
}
});
Your usage is quite strange and I guess you may want to temporarily stop sliding when you hover the banner. After checking out the documentation of unslider, I guess you may have a test on the following snippet:
$(function() {
var slidey = $('.banner').unslider({}),
data = slidey.data('unslider');
// I don't really know the relationship of $('.banner') and $('#banner') in your HTML code.
$('.banner').hover(
function() {
data.stop();
},
function() {
data.start();
}
);
});

finish animation before starting another

Problem: Whenever I click faster or slower I need last .click() call to finish before the next one starts. If you click the button faster , in the given example, you can see it's leaving divisions with 0 opacity.
What I want to achieve is stacking up till 3-4. I tried some queue code examples, couldn't make it work.
$("#addNew").click(function(){
var _this = $("#scrollable");
//Switch classes
_this.find("div.first").switchClass("first","second",500);
_this.find("div.second").switchClass("second","third",500);
_this.find("div.third").switchClass("third","fourth",500);
_this.find("div.fourth").switchClass("fourth","fifth",500);
// Insert first/new line
$("<div class='first'>Hello!</div>").css("opacity","0").hide().prependTo(_this).slideDown(function(){$(this).stop().animate({opacity:1},300)})
$("div.fifth").fadeOut().remove();
});
Here is example: http://jsfiddle.net/gtFyP/5/
Use setInterval
You could combine the below flag solution with setInterval, and thus be able to process clicks occurring during an animation.
Updated your JS Fiddle again with this alternate solution.
$(function() {
var clicking = false;
var clickCache = 0;
window.setInterval(function(){
if (!clicking && clickCache) {
processClick();
clickCache--;
}
}, 100);
var processClick = function() {
var _this = $("#scrollable");
//Switch classes
_this.find("div.first").switchClass("first", "second", 500);
_this.find("div.second").switchClass("second", "third", 500);
_this.find("div.third").switchClass("third", "fourth", 500);
_this.find("div.fourth").switchClass("fourth", "fifth", 500);
clicking = true;
// Insert first/new line
$("<div class='first'>Hello!</div>").css("opacity", "0").hide().prependTo(_this).slideDown(function() {
$(this).stop().animate({
opacity: 1
}, 300, function(){
clicking = false;
});
});
$("div.fifth").fadeOut().remove();
};
$("#addNew").click(function() {
clickCache++;
});
});
Use a Flag
You could use a flag - only start an animation if it's false. When you start animating, set it to true, when the animation is done, set it back to false.
I've modified your JS Fiddle.

How to tell .hover() to wait?

I have a drop down menu. Now when it's slided down to multiple levels, I'd like it to add wait time for like 2 secs, before it disappears, so the user can get back in, when he breaks the .hover() by mistake.
Is it possible?
my code for the slide:
$('.icon').hover(function() {
$('li.icon > ul').slideDown('fast');
}, function() {
$('li.icon > ul').slideUp('fast');
});
This will make the second function wait 2 seconds (2000 milliseconds) before executing:
$('.icon').hover(function() {
clearTimeout($(this).data('timeout'));
$('li.icon > ul').slideDown('fast');
}, function() {
var t = setTimeout(function() {
$('li.icon > ul').slideUp('fast');
}, 2000);
$(this).data('timeout', t);
});
It also clears the timeout when the user hovers back in to avoid crazy behavior.
This is not a very elegant way of doing this, however. You should probably check out the hoverIntent plugin, which is designed to solve this particular problem.
personally I like the "hoverIntent" plugin:
http://cherne.net/brian/resources/jquery.hoverIntent.html
from the page: hoverIntent is a plug-in that attempts to determine the user's intent... like a crystal ball, only with mouse movement! It works like (and was derived from) jQuery's built-in hover. However, instead of immediately calling the onMouseOver function, it waits until the user's mouse slows down enough before making the call.
Why? To delay or prevent the accidental firing of animations or ajax calls. Simple timeouts work for small areas, but if your target area is large it may execute regardless of intent.
var config = {
sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
interval: 200, // number = milliseconds for onMouseOver polling interval
over: makeTall, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )
Configuration Options
sensitivity:
If the mouse travels fewer than this number of pixels between polling intervals, then the "over" function will be called. With the minimum sensitivity threshold of 1, the mouse must not move between polling intervals. With higher sensitivity thresholds you are more likely to receive a false positive. Default sensitivity: 7
interval:
The number of milliseconds hoverIntent waits between reading/comparing mouse coordinates. When the user's mouse first enters the element its coordinates are recorded. The soonest the "over" function can be called is after a single polling interval. Setting the polling interval higher will increase the delay before the first possible "over" call, but also increases the time to the next point of comparison. Default interval: 100
over:
Required. The function you'd like to call onMouseOver. Your function receives the same "this" and "event" objects as it would from jQuery's hover method.
timeout:
A simple delay, in milliseconds, before the "out" function is called. If the user mouses back over the element before the timeout has expired the "out" function will not be called (nor will the "over" function be called). This is primarily to protect against sloppy/human mousing trajectories that temporarily (and unintentionally) take the user off of the target element... giving them time to return. Default timeout: 0
out:
Required. The function you'd like to call onMouseOut. Your function receives the same "this" and "event" objects as it would from jQuery's hover method. Note, hoverIntent will only call the "out" function if the "over" function has been called on that same run.
The general idea is to use setTimeout, like so:
$('.icon').hover(function() {
$('li.icon > ul').slideDown('fast');
}, function() {
setTimeout(function() {
$('li.icon > ul').slideUp('fast');
}, 2000);
});
But this may do counterintuitive things if the user mouses out and then mouses in again quickly—this doesn't account for clearing the timeout when the user hovers over it again. That would require additional state.
The following will stop the sliding from triggering by 2 seconds:
$('.icon').hover(function() {
$('li.icon > ul').delay(2000).slideDown('fast');
}, function() {
$('li.icon > ul').slideUp('fast');
});
$('.icon').on("mouseenter mouseleave","li.icon > ul",function(e){
var $this = $(this);
if (e.type === 'mouseenter') {
clearTimeout( $this.data('timeout') );
$this.slideDown('fast');
}else{ // is mouseleave:
$this.data( 'timeout', setTimeout(function(){
$this.slideUp('fast');
},2000) );
}
});
or you could simply use
transition:all 2s ease-in-out.
make sure that you add -webkit, -moz and -o for different browsers.
I think this is code your need:
jQuery( document ).ready( function($) {
var navTimers = [];
$('.icon').hover(function() {
var id = jQuery.data( this );
var $this = $( this );
navTimers[id] = setTimeout( function() {
$this.children( 'ul' ).slideDown('fast');
navTimers[id] = "";
}, 300 );
},
function () {
var id = jQuery.data( this );
if ( navTimers[id] != "" ) {
clearTimeout( navTimers[id] );
} else {
$( this ).children( "ul" ).slideUp('fast');
}
}
);
});
var timer;
var delay = 200;
$('#hoverelement').hover(function() {
on mouse hover, start a timeout
timer = setTimeout(function() {
Do your stuff here
}, delay);
}, function() {
Do mouse leaving function stuff here
clearTimeout(timer);
});
//edit: instert code
I would like to add to Paolo Bergantino that you can do this without the data attribut:
var timer;
$('.icon').hover(function() {
clearTimeout(timer);
$('li.icon > ul').slideDown('fast');
}, function() {
timer = setTimeout(function() {
$('li.icon > ul').slideUp('fast');
}, 2000);
});

Categories

Resources