Avoid jQuery code repeat - javascript

i am making an animated progress bar. It's code is quite simple but the problem is that I can't figure out how to avoid repeating some jQuery code, you can see it in this Fiddle:
http://jsfiddle.net/N6c2q/
basically, this is what repeats:
$('.bar-value').animate({width: '+=1%'},50,function(){
var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
var percInt = parseInt(percent);
$('.progress').text(percInt+"%");
});
that just increases the width of the inner div (progress) by 1%, and increases .progress span number by 1. Is there any way to do what i'm trying to do without repeating that code?
Thanks in advance!

Just give duration and amount you'd like to animate:
$('.bar-value').animate({width: '+=100%'},2000,function(){
var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
var percInt = parseInt(percent);
$('.progress').text(percInt+"%");
});

Use recursion:
function showProgress(finish) {
$('.bar-value').animate({
width: '+=1%'
}, 50, function () {
var percent = $('.bar-value').width() / $('.bar-value').parent().width() * 100;
var percInt = parseInt(percent);
$('.progress').text(percInt + "%");
if (percInt != 100) {
showProgress(finish);
} else {
if (finish) finish();
}
});
}
Fiddle
Edit: fix

Of course, that code is madness!!
So I would recommend you to use jQuery UI progress bar
Otherwise you can use a loop to do what you are trying to achieve:
http://jsfiddle.net/db306/N6c2q/3/
$(document).ready(function(){
var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
$('.progress').text(percent+"%");
$('button').click(function(){
$('.loader').fadeIn(1200);
$('button').attr('disabled','disabled');
for (var i=0; i<100;i++){
$('.bar-value').animate({width: '+=1%'},50,function(){
var percent = $('.bar-value').width() / $('.bar-value').parent().width()*100;
var percInt = parseInt(percent);
$('.progress').text(percInt+"%");
});
}
});
});

Related

Progress bar goes past 100

I have a progress bar in on one of my web pages. My problem with this progress bar is that if the background process takes a bit longer than expected, it will keep going and move beyond 100 percent and even out of the frame.
I use elements in a file to check and see if each criteria for the progress bar is available and then update the progress accordingly. This all works well, but no matter what I do, I still can't tell the progress bar to stop moving past 100 percent. I'm new to this of course.
Can you please help me figure this out? I've been trying to fix it for hours.
This just FYI: The back-end is written using Django and python.
Here is my code:
$(document).ready(function grabber() {
elem = document.getElementById("progress_bar_inner");
width = 1;
interval = setInterval(ajaxcall, 400);
var i;
finished = [];
addition = 0.3;
});
var ajaxcall = function getstatus () {
$("#progressText").text((width).toFixed(1) + '%');
$("#progress_bar_inner:after").css('content' , width+'%');
if (width >= 80 && finished.length <= 8){
//alert('condition triggered')
addition = 0.15;
}
width+=addition;
elem.style.width = width + '%';
$.getJSON("/some-address/status/{{some-id}}", function(data){
//console.log(data);
for (var i in data){
if(data[i]){
console.log(i);
if (!finished.includes(i)){
$('#'+i).addClass('active');
finished.push(i);
//console.log(finished);
if (width < finished.length/10*100){
width = finished.length/10*100;
}
if (finished.length === 10){
//alert('se finiiiiiiiiiiii');
width = 100;
elem.style.width = '%'+width;
$("#progress_bar_inner:after").css('content' , '%'+width);
$("#progressText").text('%'+(width).toFixed(1));
console.log(data);
clearInterval(interval);
window.location.replace("{% url "go-to-result-page" some-id %}");
}
}
}
}
});
}

jquery function doesn't trigger

My resizeAreas function doesn't trigger in $(document).ready function. Here's the link to the app. I have also tried $(document).load but same result.
This problem is not consistent. But most of the time the page doesn't load correctly. If the list of task have the same height and 4 equal(as height) lists on the row then they are loaded correctly else they're not. To make sure that you see how it must look you can move a task element from one list to another. I don't have the reputation to post images.
Here is most of the javascript code:
function makeDropArea() {
var widthArea = $(".taskListing").width() / 2 - 55;
var heightArea = $(".taskListing").height();
$('.dropArea').width(widthArea);
$('.dropArea').css('margin-left', 5 + 'px');
$('.generalInfo').css('margin-left', 5 + 'px');
$('.generalInfo').css('width', widthArea * 2 + 220 - 45);
$('.subTaskHeader').css('width', widthArea + 25);
}
function makeDropElement(){
var widthEl = $('.dropArea').width() + 25 ;
$('.task').width(widthEl);
}
function taskListingSize(){
var width = getWidth();
var height = getHeight() * 80 / 100;
$('.taskListing').css('width', width);
}
function resizeAreas() {
$('.taskListing').each(function(){
var highestBox = 0;
$('.dropArea', this).each(function(){
if($(this).height() > highestBox)
highestBox = $(this).height();
});
$('.dropArea',this).css('min-height', highestBox);
});
}
$(document).ready(function () {
menu();
taskListingSize();
makeDropArea();
makeDropElement();
resizeAreas(); //<-- this is the one with the problems
$(".dropArea").resize(resizeAreas());
$( window ).resize(function() {
taskListingSize();
makeDropArea();
makeDropElement();
});
});
Thanks.
Update 1:
I've done some more testing and this bug is only on chrome and firefox but not on IE. The problem appears only on the openshift platform.
Either change:
$(".dropArea").resize(resizeAreas());
To:
$(".dropArea").resize("resizeAreas");
Or:
$(".dropArea").resize(function(){
resizeAreas();
});
I think it should be
$(".dropArea").resize(resizeAreas);
Or
$(".dropArea").resize(function(){
resizeAreas();
});

Custom Tumblr photosets with infinite scrolling

I've been wondering how I could get this code for custom tumblr photoset sizes to work with infinite scrolling
<script type="text/javascript">
/* Photoset Resize Code by Kevin - EXCOLO.TUMBLR.COM */
$(document).ready(function() {
function photosetResize() {
$('iframe.photoset').each(function(){
var newSize = 200;
var newSrc = $(this).attr('src').replace('500',newSize);
$(this).attr('src', newSrc).width(newSize);
var high = $(this).css('height');
var calculate = parseInt(high, 10)* newSize/500;
$(this).css('height', calculate);
});
}
photosetResize();
});
</script>
I think you would need to modify it to accept a jQuery object / collection:
$(document).ready(function() {
var $iframes = $('iframe.photoset');
function photosetResize($iframes) {
$iframes.each(function(){
var newSize = 200;
var newSrc = $(this).attr('src').replace('500',newSize);
$(this).attr('src', newSrc).width(newSize);
var high = $(this).css('height');
var calculate = parseInt(high, 10)* newSize/500;
$(this).css('height', calculate);
});
}
photosetResize( $iframes );
});
You will need to find the new photosets when infinite scroll has completed via its callback.
var $newIframes = $(arrayOfNewElems).find($iframes.selector);
Hope that helps!

Jquery thumbnail scroller with buttons

I'm trying to make a jquery thumbnail scroller with buttons that work on mousedown and mouseup events . I can do the scrolling but when i try to make a function out of it to use it again n again , it dont work . Here is my code for the scroller
var $wrapper = $('.my_ul');
var $div = $('.my_div');
var $ul = $('.my_ul');
function scrollRight()
{
var divLeft = $ul.css('marginLeft');
divLeft = Math.abs(parseInt(divLeft)) - 60;
var width = $div.width();
var ulwid = $ul.width();
var ulWidth = $ul.width() - width;
if(divLeft >= ulWidth){stopScrolling();}
else{
// contintually increase scroll position*/
$wrapper.animate({'margin-left' : '-=10'}, 1, scrollRight);}
}
function scrollLeft()
{
var divLeft = $ul.css('marginLeft');
divLeft = parseInt(divLeft);
if(divLeft >= 0){stopScrolling();}
else{
// contintually increase scroll position*/
$wrapper.animate({'margin-left' : '+=10'}, 1, scrollLeft);}
}
function stopScrolling()
{
// stop increasing scroll position
$wrapper.stop();
}
$('.scroll_right').mousedown(scrollRight).mouseup(stopScrolling);
$('.scroll_left').mousedown(scrollLeft).mouseup(stopScrolling);
I need to make a function using parameters but when i try that , it dont work . Moreover , The animation gets slow because of the recursive calls . If anyone have any better solutions , please let me know .
This should work:
function scrollingStuff($right, $left, $wrapper, $div, $ul) {
$right.mousedown(scrollRight).mouseup(stopScrolling);
$left.mousedown(scrollLeft).mouseup(stopScrolling);
... put functions here ...
}
Call it with the result of a jQuery selector for the elements.
scrollingStuff($(".scroll_right"), $(".scroll_left"), ...);
This would move twice as fast:
$wrapper.animate({'margin-left' : '+=20'}, 1, scrollLeft);}
I would use a little delay. This is 1/60 sec:
$wrapper.animate({'margin-left' : '+=10'}, 16, scrollLeft);}
I also think you can move this part out of the function and not call jQuery twice. It doesn't change during the scrolling or even after loading the div and the ul's:
var width = $div.width();
var ulwid = $ul.width();
var ulWidth = ulwid - width;

Horizontal jquery scroller using position:absolute; with constant scroll

I've managed to get this far and it works great for solid width divs but can't work out how to manipulate it to work when the width of the div changes.
Question: How do I make this function take into account the different div widths after each 'round'?
var horizontalScroller = function($elem) {
var left = parseInt($elem.css("left"));
var temp = -1 * $('#horizontalScroller li').width();
if(left < temp) {
left = $('#horizontalScroller').width();
$elem.css("left", left);
}
$elem.animate({ left: (left-60) }, 2000, 'linear', function () {
horizontalScroller($(this));
});
}
$(document).ready(function() {
var i = 0;
$("#horizontalScroller li").each(function () {
$(this).css("left", i);
i += $(this).width();
horizontalScroller($(this));
});
});
Working example (with fixed width): http://jsfiddle.net/GL5V3/
Working example (with different widths): http://jsfiddle.net/wm9gt/
Well this was mildly fun, understood how your code works, but before I did that...
I rewritten it to this: (working fiddle)
function horizontalScroller(ulSelector) {
var horizontalSpan=0;
var collection=[];
function animate(index) {
var cur=collection[index];
var left=parseInt(cur.elem.css('left'));
if(left < cur.reboundPos) {
left+=horizontalSpan;
console.log(left);
cur.elem.css('left',left);
}
cur.elem.animate(
{ left: (left-60) },
2000,
'linear',
function () {animate(index)}
);
}
$(ulSelector).find('li').each(function() {
var $this=$(this);
var width=$this.width();
$this.css('left',horizontalSpan);
collection.push({reboundPos: -1 * width, elem: $this});
horizontalSpan+=width;
animate(collection.length-1);
});
console.log(collection);
console.log(horizontalSpan);
}
$(document).ready(function() {
horizontalScroller('#horizontalScroller');
});
Then I went back to your code and did this:
var horizontalSpan = 0;// swapped i for a "global" variable
var horizontalScroller = function($elem) {
var left = parseInt($elem.css("left"));
var temp = -1 * $elem.width();// updated to the correct width
if(left < temp) {// now out of bounds is properly calculated
left += horizontalSpan;// proper "wrapping" with just one addition
$elem.css("left", left);
}
$elem.animate({ left: (left-60) }, 2000, 'linear', function () {
horizontalScroller($(this));
});
}
$(document).ready(function() {
$("#horizontalScroller li").each(function () {
$(this).css("left", horizontalSpan);// horizontalSpan!!!
horizontalSpan += $(this).width();// horizontalSpan!!!
horizontalScroller($(this));
});
});
If you've got questions or want to tweak it a bit. I'd be happy you to help you along. But my hopes are that you will manage on your own.
P.S. My initial comment was rude, you're horizontal scrolling is ok thumbs up (but you were hoping the values for some of those .width() calls to be way different)

Categories