jquery handle if multiple time click - javascript

i am trying to do own slider animation of my webpage on my own js code using jquery library,I have one function, in that function i wrote move dom element using animation method with set parameter which element want animate, its working good when calling automatic repeat using setInterval, but if click next or prev button continuously on multiple time, it calling slide function continually how much time i click, so continuously calling method, collapse the css and dom elements that is making my slider ugly :(, kindly help me how can i prevent that issue, I am trying search and get that solution , but i can't get solution, Kindly help needful
click event :
$(".health-plan-slider .next").stop().click( function(){
var ele_n = $(".health-plan-slider .next").attr("data-next");
slideEffectNext( ele_n );
});
function :
function slideEffectNext(dataVal)
{
dataVal = parseInt(dataVal);
var dataValPrev = parseInt(dataVal) - 1;
if( dataVal == ele_len-1 )
{
$(".health-plan-slider .next").attr("data-next",0);
}
else
{
$(".health-plan-slider .next").attr("data-next", dataVal+1);
}
if( dataVal == 0 )
{
$(".health-plan-slider .prev").attr("data-prev", ele_len-1);
}
else
{
$(".health-plan-slider .prev").attr("data-prev", dataVal-1);
}
$(".slider-wrap .slide-elements").removeAttr("data-cur");
$(".slider-wrap .slide-elements").eq(dataVal).css("left", "920px");
$(".slider-wrap .slide-elements").eq(dataValPrev).animate({ left:-920+"px"}, 1000, function() { $(".slider-wrap .slide-elements").eq(dataValPrev).css("left",920+"px");});
$(".slider-wrap .slide-elements").eq(dataVal).animate({ left:0+"px"}, 1000).attr("data-cur", 1);
}
Advance thanks

Use
.stop()
to stop animation each time you click next or prev
$('#next').stop().click(function() {
// your animation ..
})
same for $('#prev')

try this logic
$(".health-plan-slider .next").click( function(){
if(typeof sliding != "undefined" && sliding){
var ele_n = $(".health-plan-slider .next").attr("data-next");
slideEffectNext( ele_n );
}
});
function slideEffectNext(dataVal){
sliding = true;
dataVal = parseInt(dataVal);
var dataValPrev = parseInt(dataVal) - 1;
if( dataVal == ele_len-1 )
{
$(".health-plan-slider .next").attr("data-next",0);
}
else
{
$(".health-plan-slider .next").attr("data-next", dataVal+1);
}
if( dataVal == 0 )
{
$(".health-plan-slider .prev").attr("data-prev", ele_len-1);
}
else
{
$(".health-plan-slider .prev").attr("data-prev", dataVal-1);
}
$(".slider-wrap .slide-elements").removeAttr("data-cur");
$(".slider-wrap .slide-elements").eq(dataVal).css("left", "920px");
$(".slider-wrap .slide-elements").eq(dataValPrev).animate({ left:-920+"px"}, 1000, function() { $(".slider-wrap .slide-elements").eq(dataValPrev).css("left",920+"px");});
$(".slider-wrap .slide-elements").eq(dataVal).animate({ left:0+"px"}, 1000,function(){sliding = false;}).attr("data-cur", 1);
}

Related

CSS Animation using Jquery and '.css'

So I have a piece of code. The purpose is to play a selected animation from Animate.css on click.
The code
$(".container>parent").click(function () {
$('.element').css({
'animation': 'fadeInUp .2s',
'-webkit-animation': 'fadeInUp .2s'
});
});
The problem
Animation runs, but only one time. 'Infinite' attribute causes chaos :P
What else could I do, to play that animation every single time someone click it?
Thanks for your time.
My HTML:
<span class="parent">
<img src="assets/myimage.png" class="filter-image">
<span class="element">Text</span>
</span>
I want to animate the text everytime I click it.
$(".container>parent").click(function() {
$('.element').css({
'animation': 'fadeInUp .2s',
'-webkit-animation': 'fadeInUp .2s'
});
setTimeout(function(){
$('.element').removeAttr('style');
},300);
});
The animation won't work the second time if you don't remove animation class after the current animation finishes.
But how to remove animation property after the animation finishes?
Here's a snippet:
var support = {};
support.animation = (function() {
var animationEnd = (function() {
var element = document.body || document.documentElement,
animEndEventNames = {
WebkitAnimation : 'webkitAnimationEnd',
MozAnimation : 'animationend',
OAnimation : 'oAnimationEnd oanimationend',
animation : 'animationend'
}, name;
for (name in animEndEventNames) {
if (element.style[name] !== undefined) return animEndEventNames[name];
}
}());
return animationEnd ? { end: animationEnd } : false;
})();
function animate(elem, cls, callback) {
var $elem = $(elem);
var onEndCallbackFn = function(ev) {
if (support.animation) {
$elem.removeClass(cls);
this.removeEventListener(support.animation.end, onEndCallbackFn);
}
if (callback && typeof callback === 'function') { callback.call(this, ev); }
};
if (support.animation) {
$elem.addClass(cls);
$elem[0].addEventListener(support.animation.end, onEndCallbackFn);
} else {
onEndCallbackFn();
}
}
usage is simple, just call animate function, like this:
animate($('.selector'), 'classWithAnimation', callbackFn);
In you case, you said you are using animate.css library:
$(".container>parent").click(function() {
animate($('.element'), 'animated fadeInUp', function() {
console.log('animation complete');
);
});
Live example: jsFiddle

Disable the function of a submit button in a html form with jquery, but still have it visible

As you can see in the code below, I am making an automated chat.
The user inputs text and the code responds with a message.
It's working alright so far but right now I want to prevent the user sending another message before my message appears.
So lets say the user sends a message, after that the submit button becomes disabled, preventing the user from sending more messages. When the code responds, the button comes availible again.
I don't want to hide the button, but I want to disable it's function.
That way it'd still be visible, just not functional while the function runAI is running.
If someone can help, that'd be great.
Code:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("#typing").hide();
var n = "You:<br>";
var o = $('#outputWindow');
var i = $('#inputWindow');
var s = $('#sendButton');
var t = $('#typing');
var r = -1;
//arrays
var msg = ['msg1', 'msg2', 'msg3'];
//fire send events
$(s).click(function() {
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
runAI();
}
});
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
setTimeout(function(){$('#inputWindow').hide(); }, 8000);
setTimeout(function(){$('#sendButton').hide(); }, 8000);
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
}
}
});
});//]]>
</script>
As per the latest jQuery Docs which was last updated January 26, 2015.
// Disable
$( "#sendButton" ).prop( "disabled", true );
// Enable
$( "#sendButton" ).prop( "disabled", false );
To disable the button :
$("#buttonId").prop("disabled",true);
And to enable the button :
$("#buttonId").prop("disabled",false);
I would integrate in your code like this ;
$(s).click(function() {
$("#buttonId").prop("disabled",true);
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
$("#buttonId").prop("disabled",true);
runAI();
}
});
And then when runAI() is done :
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
setTimeout(function(){$('#inputWindow').hide(); }, 8000);
setTimeout(function(){$('#sendButton').hide(); }, 8000);
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
$("#buttonId").prop("disabled",false);
}
}
document.getElementById("Submit").disabled = true;
Use:
$("#buttonId").prop("disabled",true);
To disable the button
$('input[type="submit"], input[type="button"], button').disable(true);
To enable the button again
$('input[type="submit"], input[type="button"], button').disable(false);
Of course the selector should be matching your submit button. my example would disable all buttons on your page

Hide DIVs after function has completed his task

I wrote a piece of code that auto replies to user text input.
An automated "live chat" so to say.
Though when the script runs out of responses I want it to disable the subit form and button, I don't really have any clue on how to do such a thing.
My code:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("#typing").hide();
var n = "You:<br>";
var o = $('#outputWindow');
var i = $('#inputWindow');
var s = $('#sendButton');
var t = $('#typing');
var r = -1;
//arrays
var msg = ['msg1', 'msg2', 'msg3'];
//fire send events
$(s).click(function() {
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
runAI();
}
});
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
i.val('');
i.focus();
}
}
i.focus();
});
});//]]>
</script>
The idea is to hide the submit form and button after (in the case) the script has responded with: msg1, msg2 and msg3.
If anyone can help, that'd be great !
This will do that. Place at the bottom of the runAI() function.
this will check r+1 each time runAi() is invoked. When it detects that it's greater than or equal to the message array length it will hide the user input possibilities after the last message is sent.
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
$('#inputWindow').hide();
$('#sendButton').hide();
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
}
}
When r reaches a length greater than or equal to the length of the array the input and button is hidden.
Well, simply use CSS to hide it:
$(<your object>).css('display', 'none');
use this for every object you want to hide. Go to www.w3schools.com and check out the posible values for the display property.

jQuery toggleClass with direction and animation

I've followed a tutorial to add to my site a fixed header after scroll and the logo of the site appear on the fixed part.
That works, the code:
var nav_container = $(".nav-container");
var nav = $("nav");
var logo = $("logo");
nav_container.waypoint({
handler: function(event, direction) {
nav.toggleClass('sticky', direction=='down');
logo.toggleClass('logo_sticky', direction=='down');
if (direction == 'down')
nav_container.css({ 'height' : nav.outerHeight() });
else
nav_container.css({ 'height' : 'auto' });
});
});
How can I add a delay with fade-in to the logo, so it doesn't appear suddenly?
Versions I've tried:
logo.toggleClass('logo_sticky', direction=='down').delay(500).fadeIn('slow');
logo.delay(500).toggleClass('logo_sticky', direction=='down').fadeIn('slow');
(before the toggleClass)
logo.delay(500).fadeIn('slow')
logo.toggleClass('logo_sticky', direction=='down');
(after the toggleClass)
logo.toggleClass('logo_sticky', direction=='down');
logo.delay(500).fadeIn('slow')
To be honest I've tried every single combination that came to my mind lol
new version that I'm trying that don't work either:
$(function() {
var nav_container = $(".nav-container");
var nav = $("nav");
var logo = $("logo");
$.waypoints.settings.scrollThrottle = 30;
nav_container.waypoint({
handler: function(event, direction) {
if (direction == 'down'){
nav_container.css({ 'height':nav.outerHeight() });
nav.addClass('sticky', direction=='down').stop();
logo.css({"visibility":"visible"}).fadeIn("slow");
}
else{
nav_container.css({ 'height':'auto' });
nav.removeClass('sticky', direction=='down').stop();
logo.css({"visibility":"hidden"});
}
},
offset: function() {
return (0);
}
});
});
but if I instead of fadeIn put toggle it animes the change but in a bad direction (the img appear and then toggle to disapear)
thanks
http://api.jquery.com/delay/
http://api.jquery.com/fadein/
use $(yourLogoSelector).delay(delayAmount).fadeIn();
here is proof that it works http://jsfiddle.net/6d8cf/
It seems like the fadeIn only works if you don't have the css the property visibility: hidden, but display:none...
you can do a element.hide(); and then element.fadeIn().
since the hide() changes the layout of the page because it eliminates the item from it this is the solution I came across:
$(function() {
// Do our DOM lookups beforehand
var nav_container = $(".nav-container");
var nav = $("nav");
var logo = $("logo");
$.waypoints.settings.scrollThrottle = 30;
nav_container.waypoint({
handler: function(event, direction) {
if (direction == 'down'){
nav_container.css({ 'height':nav.outerHeight() });
nav.addClass('sticky', direction=='down').stop();
logo.css('opacity',0).animate({opacity:1}, 1000);
}
else{
nav_container.css({ 'height':'auto' });
nav.removeClass('sticky', direction=='down').stop();
logo.css('opacity',1).animate({opacity:0}, 1000);
}
},
offset: function() {
return (0);
}
});
});

jQuery detect how many seconds a mouse stays over element

is there any way to detect how many seconds a mouse pointer stays on an html element?
I would like to retrieve how many seconds a mouse stays over element to put a little delay on a callback event... if is possible :)
i'm trying with a simple for() cycle detecting by a counter :
var time_over ;
$('.bean-active').live('mouseover',function(){
id_tag = $(this).attr("id");
for(time_over = 1;time_over <= 3000;time_over ++){
if(time_over == 3000){
$('.bean-bubble,.bean-bubble img').hide();
$('#bean-bubble-'+id_tag+',#bean-bubble-'+id_tag+' img').show();
}
}
});
the problem is that it doesn't works :(
also i would like to bind a mouseleave event, script logic should be:
while ( mouseover element count how many time it stays over)
if (time == n)
{ do somenthing }
if (mouseleave from element earlier then time)
{ do somenthing different }
Given this markup:
<div id="hoverOverMe">Hover over me</div>
<div id="output"></div>
Something like this plugin should do the trick:
(function($) {
$.fn.delayedAction = function(options)
{
var settings = $.extend(
{},
{
delayedAction : function(){},
cancelledAction: function(){},
hoverTime: 1000
},
options);
return this.each(function(){
var $this = $(this);
$this.hover(function(){
$this.data('timerId',
setTimeout(function(){
$this.data('hover',false);
settings.delayedAction($this);
},settings.hoverTime));
$this.data('hover',true);
},
function(){
if($this.data('hover')){
clearTimeout($this.data('timerId'));
settings.cancelledAction($this);
}
$this.data('hover',false);
} );
});
}
})(jQuery);
and the calling code:
$('#hoverOverMe').delayedAction (
{
delayedAction: function($element){
$('#output').html($element.attr('id') + ' was hovered for 3 seconds');
},
cancelledAction: function($element){
$('#output').html($element.attr('id') + ' was hovered for less than 3 seconds');
},
hoverTime: 3000 // 3 seconds
}
);
Live example: http://jsfiddle.net/nrUqS/
For your requirement, something like this should suffice:
$('.bean-active').delayedAction(
{
delayedAction: function($element){
id_tag = $element.attr("id");
$('.bean-bubble,.bean-bubble img').hide();
$('#bean-bubble-'+id_tag+',#bean-bubble-'+id_tag+' img').show();
},
hoverTime: 3000
});
This code will calculate the time in milliseconds that you hover over an element with your mouse:
$(document).ready(function() {
$('#element').bind('mouseenter mouseleave', function(evt) {
var currentTime == new Date();
if (evt.type === 'mouseenter') {
$(this).data('mouseenterTime') == currentTime.getTime();
} else if (evt.type === 'mouseleave') {
var mouseoverTime = currentTime.getTime() - $(this).data('mouseenterTime');
alert('mouseover time was: ' + mouseoverTime);
}
})
});
You should be able to utilize the hover() function to capture when the mouse goes over a particular element and then react as desired when the mouse is removed from that object.
$("#someDiv").hover(function(){
//start counter
}, function(){
//stop counter
});
I've used C. Spencer Beggs answer as a template, because his one didn't work for me. I've used simple variables, included lots of console.log messages and corrected '==' code to '='. This example will wait 3 seconds of 'hover over a link' action to take place before acting. HTH someone.
var mouseenterTime = 0;
$(document).on('mouseenter mouseleave', '#element', function (evt)
{
var currentTime = new Date();
if (evt.type === 'mouseenter')
{
mouseenterTime = currentTime.getTime();
console.log('mouseenterTime (#1): ' + mouseenterTime);
} else if (evt.type === 'mouseleave') {
console.log('mouseenterTime (#2): ' + mouseenterTime);
var mouseoverTime = currentTime.getTime() - mouseenterTime;
console.log('mouseover time was: ' + mouseoverTime);
// Checking if the Hover action has latest for longer than 3 seconds.
if(mouseoverTime > 3000) {console.log("Three seconds have elapsed")}
}
})

Categories