jQuery bug when using bounce effect - javascript

I have problem with jQuery bounce effect. Every thing works good when there is no bounce - with bounce, when You move very fast many times on button - in sometime, box just doesn't hide. What is wrong in this jsfiddle?
My jsfiddle:
http://jsfiddle.net/d6mSA/170/
My JS:
$('.flex_section').delegate('a','mouseenter mouseleave',function(e){
var a = $(this).attr('id');
if (e.type == 'mouseenter'){
clearTimeout(t_on)
if (a == 'abc'){
clearTimeout(t_off)
t_on = setTimeout(function() { popup_show(a,t_on); }, 10);
}
} else {
t_off = setTimeout(function() { popup_remove(a,t_off); }, 1000);
}
)}
function popup_show(type,string){
if (type == 'abc'){
$('#pc_' + type).css('display','block');
$('#pc_' + type).effect( "bounce",{times:3,distance:20},1000);
}
clearTimeout(string);
}
function popup_remove(type,string){
$('#pc_' + type).css('display','none');
clearTimeout(string)
}

Keep it simple:
function popup(){
$('.flex_top a').hover(function(){
var type = $(this).attr('id');
var offset = $('#' + type).offset();
$('#id_' + type).css('display','block')
.offset({left:offset.left + 100, top:offset.top + 380})
.effect( "bounce",{times:3,distance:20},1000);
},function(){
var type = $(this).attr('id');
$('#id_' + type).fadeOut();
}
);
}
And dont call many times the same object search $('#id_' + type)

Try using stop
$('#pc_' + type).stop().effect( "bounce",{times:3,distance:20},1000);

Related

Timer for individual <div>

I'm currently trying to set a timer for each div created, whereby each div has a background color of green or red depending on if there are detections in the webRTC video. Is there a way to assign a timer to the divs individually? Or maybe to only check for my own video? I've tried something like below, but it does not work when there are more than 1 people in the call, as "time" will be a global variable. I've also tried something like time = Math.ceil((time+1)/checkerBox.length) , but it does not seem to work too. Any pointers will be helpful
function checker(){
var time =0;
var timer = setInterval(function (){
for(var i=0;i<checkerBox.length;i++){
if(checkerBox[i].style.backgroundColor=="red"){
time = time + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + checkerBox[i].innerHTML + " seconds");
}else{
time = 0;
}
//Exceed time
if(checkerBox[i].innerHTML == 30){
setTimeout(function(){
takeScreenshot(videoNum[i-1]);
}, 100);
time = 0;
}
checkerBox[i].innerHTML = time;
}
},1000)
}
Update : I ended up using arrays
var takenFrom;
var d = new Date();
let timeKeep = new Array(0,0,0,0,0,0,0,0,0,0,0);
let screenShots = new Array(0,0,0,0,0,0,0,0,0,0,0);
function checker(){
timer = setInterval(function (){
for(var i=0;i<=(checkerBox.length)-1;i++){
tableRow[i+1].cells[2].innerHTML = timeKeep[i]
tableRow[i+1].cells[3].innerHTML = screenShots[i]
if(flag[i].innerHTML=="0"){
checkerBoxFalse(checkerBox[i]);
timeKeep[i] = timeKeep[i] + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + tableRow[i+1].cells[2].innerHTML + " seconds");
if(tableRow[i+1].cells[2].innerHTML == 10 ){
takenFrom = "Box" + videoNum[i].innerHTML + "minute" + d.getMinutes() + " room" + ROOM_ID
takeScreenshot(videoNum[i],takenFrom);
screenShots[i] = screenShots[i] + 1;
timeKeep[i] = 0;
}
} else if(flag[i].innerHTML== "1"){
checkerBoxTrue(checkerBox[i]);
timeKeep[i] = 0;
}
}
},1000)
}
Yes:
for (let div of divs) {
setInterval(function() {
//do something with div
}, 1000);
}
let is block scoped, so each setInterval will have its own div.

jQuery Animated Text Colors

I'm trying to get each letter color to swap from red to green and back to red.
What I have now works, but I don't like the fading, is there a better way to do this?
const ltr = $('h1').text().split('');
function colorChange() {
$( 'h1' ).fadeOut(500, function() {
redGreen();
}).fadeIn(500).fadeOut(500, function() {
greenRed();
}).fadeIn(500);
}
setInterval( function() {
colorChange();
}, 1);
function redGreen() {
$('h1').text('');
for(var i = 0; i < ltr.length; i++) {
if(i % 2 == 0) {
$('h1').append('<span class="red">' + ltr[i] + '</span>');
} else {
$('h1').append('<span class="green">' + ltr[i] + '</span>');
}
}
}
function greenRed() {
$('h1').text('');
for(var i = 0; i < ltr.length; i++) {
if(i % 2 == 0) {
$('h1').append('<span class="green">' + ltr[i] + '</span>');
} else {
$('h1').append('<span class="red">' + ltr[i] + '</span>');
}
}
}
Referred to the solution for toggling class animation here : ToggleClass animate jQuery?. You should change your colorChange function to something like this :
function colorChange() {
$( 'h1 > span' ).toggleClass( "red green", 1000, "easeInOutQuad" );
}
And make sure you build the spans at the beginning with alternative classes to each item (use one of your redGreen() or greenRed() function for the first time only).
Check this Fiddle
You need to include jQuery UI to have the effect.
I managed to remove the fade effect by using setTimeout.
See the plunker here

how do I cycle through background images by clicking a button?

I want to preview some backgrounds by using a button to cycle through them, just not very good at the js. I have them named "1"-"13". I wanted to step through them. When I get to "13" I want it to set it back to "1" when "next" is clicked and when "prev" is clicked when it gets to "1" to set it to "13". This is what I've tried but I know my syntax is wrong for the js.
HTML
<button id="n" class="b">NEXT</button>
<button id="p" class="b">PREV</button>
CSS
body {
background:black;
}
.b {
background:black;
color:white;
}
JS
$(document).ready(function(){
var i = 1;
$("#n").click(function() {
alert(i);
i++;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===14){i=1;};
});
$("#p").click(function() {
alert(i);
i--;
$('body').css("background-image", "url(../images/bg/ " + i + " .png)");
if (i===0){i=13;};
});
});
Still working on it but some help would be nice getting it done faster.
http://jsfiddle.net/80nz56wy/ I guess a jsfiddle won't help much if I'm using local content.
You should also try this. Here conditions are written before setting CSS, which will check first and then assign the image path.
$(document).ready(function() {
var i = 0;
$("#n").click(function() {
i++;
if (i > 13){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 13){ i = 1; };
});
$("#p").click(function() {
i--;
if (i <= 0) { i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
//if (i === 1) { i = 13; };
});
});
Other wise you may get wrong image paths, something like:
images/bg/0.png
or
images/bg/-1.png
Change Your javascript coding as below..
var i = 1;
$("#n").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i+1;
if (i==13){i=1};
});
$("#p").click(function() {
$('body').css("background-image", "bg" + i +".png");
i=i-1;
if (i==1){i=13};
});
Here it is, not sure what I changed the 20 times I edited the same line over and over but I must have gone full retard earlier.
$(document).ready(function(){
var i = 0;
$("#n").click(function() {
i++;
if ( i > 13 ){ i = 1; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
$("#p").click(function() {
i--;
if ( i <= 0 ){ i = 13; };
$('body').css('background-image', 'url(images/bg/' + i + '.png)');
});
});

Animating an image carousel

I am using and have modified an image slider/carousel and need some guidance one two things. I need to enable it to auto scroll through the images firstly. and secondly I need to have three words underneath that act as controls too. So if I click on one it will take me to that image in the slider with some text underneath?
Example Fiddle
(function() {
var first = $('.item').first(),
last = $('.item').last(),
itemWidth = first.width(),
carousel = $('.carousel');
carousel.prepend(last.clone()).append(first.clone());
carousel.width(itemWidth * $('.item').length);
carousel.css({left: -itemWidth});
$('.prev').on('click', function(e){
e.preventDefault();
carousel.animate({left: '+=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left) < 2) {
carousel.css({left: -itemWidth * (carousel.children().length - 2)});
}
});
return false;
});
$('.next').on('click', function(e){
e.preventDefault();
carousel.animate({left: '-=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left + itemWidth * (carousel.children().length - 1)) < 2) {
carousel.css({left: -itemWidth});
}
});
return false;
});
})();
so the image illustrates my aim.
Easiest way:
Create variable var autoplay=true;,
Wrap Your function binded to next button click in setInterval, so setInterval Function would be like this one:
setInterval(function(){
if(!autoplay)return;
carousel.animate({left: '-=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left + itemWidth * (carousel.children().length - 1)) < 2) {
carousel.css({left: -itemWidth});
}
})
},1000)
and then just add autoPlay toggle handler
$('.autoplayControl').on('click',function(){
autoplay=!autoplay;
})
FIDDLE: http://jsfiddle.net/UWbrQ/197/
Since I hadn't seen the button for autoplay I thought of automatic solution.
In This fiddle the Gallery moves with automatic movement(ten second for image) when the user clicks on pre next buttons auto move stops to restart after 10 seconds of inactivity
For me this is a more elegant solution
<script type="text/javascript">
$(document).ready(function(){
var first = $('.item').first(),
last = $('.item').last(),
itemWidth = first.width(),
carousel = $('.carousel');
console.log(itemWidth)
carousel.prepend(last.clone()).append(first.clone());
carousel.width(itemWidth * $('.item').length);
carousel.css({left: -itemWidth});
//auto start
var giranews = setInterval(function(){move()},5000);
function move(){
carousel.animate({left: '-=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left + itemWidth * (carousel.children().length - 1)) < 2) {
carousel.css({left: -itemWidth});
}
});
};
function stopx(){
clearInterval(giranews);
};
function countdown(a) {
var count = a;
timerId = setInterval(function() {
count--;
console.log(count);
if(count == 0) {
clearInterval(timerId);
giranews = setInterval(function(){move()},5000);
};
}, 1000);
};
$('.prev').on('click', function(e){
e.preventDefault();
stopx();
if(typeof timerId!=='undefined'){clearInterval(timerId);countdown(10)}else{countdown(10)}
carousel.animate({left: '+=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left) < 2) {
carousel.css({left: -itemWidth * (carousel.children().length - 2)});
}
});
return false;
});
$('.next').on('click', function(e){
e.preventDefault();
stopx();
if(typeof timerId!=='undefined'){clearInterval(timerId);countdown(10)}else{countdown(10)}
carousel.animate({left: '-=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left + itemWidth * (carousel.children().length - 1)) < 2) {
carousel.css({left: -itemWidth});
}
});
return false;
});
})
</script>
The Easiest Way Demo Based On your Code with Just Addition of few Lines
Periodically Call the auto function
This function is basically the content inside your click for next slide
Wrap this inside the function and call it with your required interval
setInterval(Auto,5000);
function Auto(){
carousel.animate({left: '-=' + itemWidth}, 300, function(){
if(Math.abs(carousel.position().left + itemWidth * (carousel.children().length - 1)) < 2) {
carousel.css({left: -itemWidth});
}
});
}
Although the aim of this community is not provide complete script to other people, but provide solutions to specific problems, given my love for web galleries in this fiddle there is a gallery with caption below the image with buttons that move images
To accomplish this i had to change the script logic and code is increased slightly
If you like this solution don't forget to flag in green my answer ;) thanks
<script type="text/javascript">
$(document).ready(function(){
var first = $('.item').first(),
last = $('.item').last(),
itemWidth = first.width(),
countx=1,
carousel = $('.carousel');
console.log(carousel.position().left)
carousel.width(itemWidth * $('.item').length);
//auto start
var giranews = setInterval(function(){move()},5000);
function move(){
var left=carousel.position().left
if(left<(itemWidth*($('li.item').length-2)*-1)){carousel.animate({'left':'0px'},300)}else{ carousel.animate({left: '-=' + itemWidth}, 300);}
if(countx===4){countx=1}else{countx++}
showCaption(countx)
};
function stopx(){
clearInterval(giranews);
};
function countdown(a) {
var count = a;
timerId = setInterval(function() {
count--;
console.log(count);
if(count == 0) {
clearInterval(timerId);
giranews = setInterval(function(){move()},5000);
};
}, 1000);
};
//show captions in caption div
function showCaption(countx){
var caption=$('li:eq('+(countx-1)+')').attr('data-caption')
$('#caption').text(caption)
}
showCaption(countx)
$('.prev').on('click', function(e){
e.preventDefault();
stopx();
if(typeof timerId!=='undefined'){clearInterval(timerId);countdown(10)}else{countdown(10)}
if(countx===1){countx=4}else{countx--}
showCaption(countx)
var left=carousel.position().left
if(left===0){carousel.animate({'left':(itemWidth*($('li.item').length-1)*-1)+'px'},300)}else{carousel.animate({left: '+=' + itemWidth}, 300);}
});
$('.next').on('click', function(e){
e.preventDefault();
stopx();
if(typeof timerId!=='undefined'){clearInterval(timerId);countdown(10)}else{countdown(10)}
if(countx===4){countx=1}else{countx++}
showCaption(countx)
var left=carousel.position().left
if(left<(itemWidth*($('li.item').length-2)*-1)){carousel.animate({'left':'0px'},300)}else{carousel.animate({left: '-=' + itemWidth}, 300);}
});
//insert buttons links to image
for(a=0;a<$('li.item').length;a++){
$('<a class="butt">'+(a+1)+'</a>').appendTo('div.buttons')
}
$('a.butt').click(function(e){
e.preventDefault();
stopx();
if(typeof timerId!=='undefined'){clearInterval(timerId);countdown(10)}else{countdown(10)}
var pos=carousel.position().left
carousel.animate({'left': (($(this).index()*itemWidth)*-1)+'px'})
showCaption($(this).index()+1)
countx=$(this).index()+1
})
})
</script>

jquery prototype for a commonly used function

I'm not too experienced in JQuery beyond standard api functionality, but I have a number of scrollers on my page which all use the same code, only they each have a few of their own settings (for example, separate heights and scroll limits, and current number of times they have been scrolled). I want to be able to use the code over and over again, but with each reference receiving its own set of variables. I think that prototypes are what I'm after, but I can't quite wrap my head around the examples I've seen of this. This is my scroller code:
$(document).ready(function() {
var scrollAmt = 50; //distance in pixels;
var scrollableAmt = $('#weblinks .container').outerHeight();
var viewAmt = $('#weblinks').outerHeight();
var maxScroll = Math.ceil((scrollableAmt-viewAmt) / scrollAmt);
var currentItem = 0;
function setScrollButtons(scrollRef,scrollAmount){
}
$("#weblinks .scrollDownBtn").click(function(){
if (currentItem <= maxScroll){
$('#weblinks .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){
currentItem++
});
} else {
currentItem = 0;
$('#weblinks .container:not(:animated)').animate({'top' : currentItem},500);
}
});
$("#weblinks .scrollUpBtn").click(function(){
if (currentItem > 0){
$('#weblinks .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){
currentItem--;
});
} else {
$('#weblinks .container:not(:animated)').animate({'top' : currentItem},500);
}
});
});
So essentially what I'd want to do is create a function or class, I guess, which accomplishes all of the above code, but be able to pass it a div reference to take the place of #weblinks, and maybe pass it a scroll amount, and multiple instances of this functionality be able to exist on the same page together. Anybody have any advice about the best way to go about this?
EDIT: I've added the HTML that will always exist for each scroller.
<div id="weblinks" class="scrollbar_container">
<div class="customScrollBox">
<div class="container">
<div class="content">
</div>
</div>
<a class="scrollUpBtn" href="javascript:void(0);"></a> <a class="scrollDownBtn" href="javascript:void(0);"></a>
</div>
</div>
My Bid:
(function($){
$.fn.extend({
customScroller: function(options){
return this.each(function(i,e){
var container = $(e).find('.container'),
content = $(e).find('.content'),
scrollUpBtn = $(e).find('.scrollUpBtn'),
scrollDownBtn = $(e).find('.scrollDownBtn');
var self = $(e);
var o = $.extend({}, $.fn.customScroller.defaults, options);
o.scrollableAmt = container.outerHeight();
o.viewAmt = self.outerHeight();
o.maxScroll = Math.ceil((o.scrollableAmt - o.viewAmt) / o.scrollAmt);
scrollDownBtn.click(function(){
console.log('DOWN -- current: '+o.currentItem);
if (o.currentItem <= o.maxScroll){
container.filter(':not(:animated)').animate({
top: '-='+o.scrollAmt
},500,function(){
o.currentItem++;
});
}else{
o.currentItem = 0;
container.filter(':not(:animated)').animate({
top: o.currentItem
},500);
}
});
scrollUpBtn.click(function(){
console.log('UP -- current: '+o.currentItem);
if (o.currentItem > 0){
container.filter(':not(:animated)').animate({
top: '+='+o.scrollAmt
},500,function(){
o.currentItem--;
});
}else{
container.filter(':not(:animated)').animate({
top: o.currentItem
},500);
}
});
});
}
});
$.fn.customScroller.defaults = {
scrollAmt: 50,
scrollableAmt: 0,
viewAmt: 0,
maxScroll: 0,
currentItem: 0
};
})(jQuery);
$('#weblinks').customScroller();
To answer your question, I use extend in a couple of places: one for the options, and the other for jQuery addon ability.
$.fn.extend tells jQuery this is extending its functionality.
$.extend({},$.fn.customScroller.defaults, option); allows you to call .customScroller({ scrollAmount: 10 }) and change the behavior of the scroll.
any other questions, please just ask.
This is a good candidate for jQuery plugin you can create for yourself. Of course if you want to spend some time and learn this principle :)
How to develop a jQuery plugin for some details of what and how jQuery plugins do
You could pretty simply refactor it in the case that all div's will have a sub container class. Something like:
function scrollExample(divId) {
var scrollAmt = 50; //distance in pixels;
var scrollableAmt = $(divId + ' .container').outerHeight();
var viewAmt = $(divId).outerHeight();
var maxScroll = Math.ceil((scrollableAmt-viewAmt) / scrollAmt);
var currentItem = 0;
function setScrollButtons(scrollRef,scrollAmount){
}
$(divId + " .scrollDownBtn").click(function(){
if (currentItem <= maxScroll){
$(divId + ' .container:not(:animated)').animate({'top' : '-='+ scrollAmt + ''},500,function(){
currentItem++
});
} else {
currentItem = 0;
$(divId + ' .container:not(:animated)').animate({'top' : currentItem},500);
}
});
$(divId + " .scrollUpBtn").click(function(){
if (currentItem > 0){
$(divId + ' .container:not(:animated)').animate({'top' : '+='+ scrollAmt + ''},500,function(){
currentItem--;
});
} else {
$(divId + ' .container:not(:animated)').animate({'top' : currentItem},500);
}
});
});
Then call it with something like:
$(document).ready(function() {
scrollExample('#webLinks');
}
If you had the actual reference to the object it would be slightly different, but still follow a similar principle.

Categories