How to put in previous and next function - javascript

Can someone give me a hand with this script? I wonder how to put in previous and next function? Start and stop function is working great. Hope that script is readable ok.
Another question.
Is it possible to make previous and next function like when you press previous bttn that script stops and you need to press play bttn to start it again?
Thanks for help.
<script type="text/javascript">
// SET THIS VARIABLE FOR DELAY, 1000 = 1 SECOND
var delayLength = 10000;
function doMove(panelWidth, tooFar) {
var leftValue = $("#mover").css("left");
// Fix for IE
if (leftValue == "auto") { leftValue = 0; };
var movement = parseFloat(leftValue, 10) - panelWidth;
if (movement == tooFar) {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": 0
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
else {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": movement
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
}
jQuery(function($){
var $slide1 = $("#slide-1");
var panelWidth = $slide1.css("width");
var panelPaddingLeft = $slide1.css("paddingLeft");
var panelPaddingRight = $slide1.css("paddingRight");
panelWidth = parseFloat(panelWidth, 10);
panelPaddingLeft = parseFloat(panelPaddingLeft, 10);
panelPaddingRight = parseFloat(panelPaddingRight, 10);
panelWidth = panelWidth + panelPaddingLeft + panelPaddingRight;
var numPanels = $(".slide").length;
var tooFar = -(panelWidth * numPanels);
var totalMoverwidth = numPanels * panelWidth;
$("#mover").css("width", totalMoverwidth);
$("#slider").append('Stop');
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$("#slider-stopper").click(function(){
if ($(this).text() == "Stop") {
clearInterval(sliderIntervalID);
$(this).text("Start");
}
else {
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$(this).text("Stop");
}
});
});
</script>

Related

disable the .click event after the first use

I am trying to adapt this js code to disable the .click event after you click the button. I am a beginner with js and realy only have a basic understanding. I have tried to use an if statement but that didn't work.
here is the js code:
var sec = ["30% ENTER KEYCODE: Thirty", "25% ENTER KEYCODE: Twenty-five", "20% ENTER KEYCODE: Twenty","15% ENTER KEYCOVE: Fifteen","10% ENTER KEYCODE: Ten","5% EMTER KEYCODE: Five"];
var offset = 30;
//set default degree (360*5)
var degree = 1800;
//number of clicks = 0
var clicks = 0;
$(document).ready(function(){
/*WHEEL SPIN FUNCTION*/
$('#spin').click(function(){
//add 1 every click
clicks ++;
/*multiply the degree by number of clicks
generate random number between 1 - 360,
then add to the new degree*/
var newDegree = degree*clicks;
var extraDegree = Math.floor(Math.random() * 360) + 1;
totalDegree = newDegree+extraDegree;
var colorIndex = Math.ceil(((totalDegree+30) % 360) / 60) -1;
var colorPrev = colorIndex == 0 ? 5 : colorIndex - 1;
var colorNext = colorIndex == 5 ? 0 : colorIndex + 1;
offset = (extraDegree % 60);
var result = sec[colorIndex];
if(offset == 0) {
result ;
} else if (offset <= 30) {
result ;
} else {
result ;
}
$("#answer").html("Answer: " + result);
/*let's make the spin btn to tilt every
time the edge of the section hits
the indicator*/
$('#wheel .sec').each(function(){
var t = $(this);
var noY = 0;
var c = 0;
var n = 700;
var interval = setInterval(function () {
c++;
if (c === n) {
clearInterval(interval);
}
var aoY = t.offset().top;
console.log(aoY);
/*23.7 is the minumum offset number that
each section can get, in a 30 angle degree.
So, if the offset reaches 23.7, then we know
that it has a 30 degree angle and therefore,
exactly aligned with the spin btn*/
if(aoY < 23.89){
console.log('<<<<<<<<');
$('#spin').addClass('spin');
setTimeout(function () {
$('#spin').removeClass('spin');
}, 100);
}
}, 10);
$('#inner-wheel').css({
'transform' : 'rotate(' + totalDegree + 'deg)'
});
noY = t.offset().top;
});
});
});//DOCUMENT READY
here is the original post that I am trying to adapt
https://codepen.io/anon/pen/JGwQva
again I am trying to disable the ability to spin the wheel after you click the spin button.
If you only want to use it once there is a one() method that removes listener after first click
Change:
$('#spin').click(function(){
To
$('#spin').one('click',function(){
There are several hints given by other moderators. Anyways, you may try any of these, lets if this helps.
Simple solution using disabled attribute comes handy.
$(function() {
$('#spin').click(function() {
console.log('clicked..', this);
$(this).prop('disabled', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.one.
$(function() {
$('#spin').one('click', function() {
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.on and $.off.
$(function() {
$('#spin').on('click', function() {
console.log('clicked..', this);
$(this).off('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using some class names.
$(function() {
$('#spin').click(function() {
if ($(this).hasClass('hold')) {
return;
}
$(this).addClass('hold');
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
$('#spin').click(function(){
clicks ++;
if (clicks < 1 ) {
//rest of You code and/or reset clicks variable
}
}
also, change click to $('#spin').on('click',function(){}
var clicks = 0;
$(function () {
$('body').on('click', '#spin', function () {
//
if (clicks > 0) {
return false;
}
// write code here for first click
clicks++;
})
})

Animation ( bar fills up over time ) with Jquery (Suggestion)

I would like to replicate the same functionality as at ign.com, where the indicator bar fills up over time. I got it working but I got some sync issues after a while. So i'm open to suggestions to do it from scratch (I'm beginner with all this animation stuff).
This is the code.
function GoProgressBar() {
var $lineStatus = $('.featured-articles-line-status');
$lineStatus.css('width', '0px');
$lineStatus.animate({ width: '694px' }, 12000, 'linear', GoProgressBar);
};
function GoOverlay(width, isLast, currentWidth) {
var $overlayLine = $('.status-overlay');
if (isLast) {
$overlayLine.css('width', '0px');
return;
}
if (currentWidth) {
$overlayLine.css('width', currentWidth);
$overlayLine.animate({ width: width }, 700);
} else {
$overlayLine.css('width', '0px');
$overlayLine.animate({ width: width }, 700);
}
};
function ShowNextElement() {
var $elements = $('.element'),
$overlayLine = $('.status-overlay'),
$liElements = $('#elements li'),
width;
if (currentElement === elements[elements.length - 1]) {
currentWidth = $overlayLine.width() + 'px',
width = currentWidth + $($liElements[(elements.length - 1)]).outerWidth() + 'px';
GoOverlay(width, true, currentWidth);
currentElement = elements[0];
$elements.hide();
$(currentElement).fadeIn(1000);
return;
}
i = elements.indexOf(currentElement) + 1;
var currentTab = $liElements[(i - 1)],
currentWidth = $overlayLine.width();
if (currentWidth) {
width = currentWidth + $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, currentWidth);
} else {
width = $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, false);
}
currentElement = elements[i];
$elements.hide();
$(currentElement).fadeIn(1000);
}
Thanks!
http://jqueryui.com/progressbar/
You could try this..
There are more features in addition to this,check it out.
Might come useful :)
There are a wealth of ways in which you could do this.
You should have some kind of controller to manage the show and hide.
var Application = {
show : function() {
jQuery('.application-overlay').stop().animate({ top: 40 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 1000},500);
},
hide : function() {
jQuery('.application-overlay').stop().animate({ top: -1200 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 200},500);
}
};
Then you have your triggers : Application.show();
jQuery(document).ready(function() {
jQuery('.cf-speakers .span2 a').hover(function() {
jQuery('span',this).stop().animate({ opacity: 1.0 },100);
}, function() {
jQuery('span',this).stop().animate({ opacity: 0.0 },100);
});;
jQuery('.apply-now').click(function(e) {
Application.show();
e.stopPropagation();
e.preventDefault();
});
jQuery('body').click(function(e) {
var application = jQuery('.application-overlay');
if( application.has(e.target).length === 0)
Application.hide();
});
jQuery('.gallery a').click(function(e) {
var src = jQuery(this).attr('href');
jQuery('.main-container img').hide().attr('src', src).fadeIn('fast');
jQuery('.gallery a').each(function() {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
e.stopPropagation();
e.preventDefault();
});
});
Your css would of course come into play also but that can be left to you!
This should give you an example of what you need .. But you're already on the right track, sometimes there is merit in reusing other people code too you know! :)

Memory leak with jquery fixed table header, AJAX setInterval

I use the below fixedtableheader plugin on a golf leaderboard page that uses AJAX and setInterval to fetch score changes from the server. Without the plugin everything works well, with the plugin, there is a constant memory leak that during the course of the day make Firefox go from 60MB at start to 1.5GB before end of day and crash. Can anyone spot any memory leaks in this code?
The page in question is http://scoring.pgalinks.net/leaderboards/lobby.cfm?from=so
jQuery.fn.fixedtableheader = function (options) {
var settings = jQuery.extend({
headerrowsize: 1,
highlightrow: false,
highlightclass: "highlight"
}, options);
this.each(function (i) {
var $tbl = $(this);
var $tblhfixed = $tbl.find("tr:lt(" + settings.headerrowsize + ")");
var headerelement = "th";
if ($tblhfixed.find(headerelement).length == 0) headerelement = "td";
if ($tblhfixed.find(headerelement).length > 0) {
$tblhfixed.find(headerelement).each(function () {
$(this).css("width", $(this).width());
});
var $clonedTable = $tbl.clone().empty();
var tblwidth = GetTblWidth($tbl);
$clonedTable.attr("id", "fixedtableheader" + i).css({
"position": "fixed",
"top": "0",
"left": $tbl.offset().left
}).append($tblhfixed.clone()).width(tblwidth).hide().appendTo($("body"));
if (settings.highlightrow) $("tr:gt(" + (settings.headerrowsize - 1) + ")", $tbl).hover(function () {
$(this).addClass(settings.highlightclass);
}, function () {
$(this).removeClass(settings.highlightclass);
});
$(window).scroll(function () {
if (jQuery.browser.msie && jQuery.browser.version == "6.0") $clonedTable.css({
"position": "absolute",
"top": $(window).scrollTop(),
"left": $tbl.offset().left
});
else $clonedTable.css({
"position": "fixed",
"top": "0",
"left": $tbl.offset().left - $(window).scrollLeft()
});
var sctop = $(window).scrollTop();
var elmtop = $tblhfixed.offset().top;
if (sctop > elmtop && sctop <= (elmtop + $tbl.height() - $tblhfixed.height())) $clonedTable.show();
else $clonedTable.hide();
});
$(window).resize(function () {
if ($clonedTable.outerWidth() != $tbl.outerWidth()) {
$tblhfixed.find(headerelement).each(function (index) {
var w = $(this).width();
$(this).css("width", w);
$clonedTable.find(headerelement).eq(index).css("width", w);
});
$clonedTable.width($tbl.outerWidth());
}
$clonedTable.css("left", $tbl.offset().left);
});
}
});
function GetTblWidth($tbl) {
var tblwidth = $tbl.outerWidth();
return tblwidth;
}
};

jQuery rearrange DOM elements

I'm a little confused why this is not working how it's supposed to.
I have a list of <div>s that wrap around based on the size of the page. But clicking the div it .animate() the width of the clicked div and animates the divs after it closer together and stacks them.
This all works except the last stacked div, despite having plenty of room still gets knocked down to the next row.
please see my code on jsfiddle:
http://jsfiddle.net/ZHYRq/2/
$.each($('.employee-box'), function(i, el) {
$(el).addClass("top-" + (Math.round($(el).offset().top)));
return $(el).css('position', 'relative').attr('data-left', Math.round($(el).offset().left));
});
$('.employee-image').hover(function(e) {
var $employee;
$employee = $(e.target).parents('.employee-box');
if (e.type === 'mouseenter') {
return $($employee.find('a.bio')).addClass('highlight');
} else {
return $($employee.find('a.bio')).removeClass('highlight');
}
});
$('.employee-image, a.bio').click(function(e) {
var $employee, is_expanded, speed;
speed = 150;
$employee = $(e.target).parents('.employee-box');
is_expanded = $employee.hasClass('bio-expanded');
if ($('.bio-expanded').length > 0) {
$.when(collapse_previous_bio(speed)).then(function() {
if (!is_expanded) {
return expand_bio_box($employee, speed);
}
});
} else {
expand_bio_box($employee, speed);
}
return false;
});
var collapse_previous_bio = function(speed) {
var klass;
klass = "." + $('.bio-expanded').attr('class').match(/top-\d{1,5}/)[0];
$('.bio-expanded .bio-block').fadeOut(speed, function() {
$('.bio-expanded').animate({
width: "185px"
}, speed);
$(klass).animate({
left: '0px'
}, speed);
$('.bio-expanded').removeClass('bio-expanded');
});
};
var expand_bio_box = function($employee, speed) {
var curr_left, klass;
klass = "." + $employee.attr('class').match(/top-\d{1,5}/)[0];
curr_left = parseInt($employee.data('left'));
// comment out the $.when block and un-comment out the collapse_others() to see the other elements collapse as they should
$.when(collapse_others(klass, curr_left)).then(function() {
$employee.animate({
width: "392px"
}, speed, function() {
$employee.find('.bio-block').fadeIn(speed);
$employee.addClass('bio-expanded');
});
});
// collapse_others(klass, curr_left)
};
var collapse_others = function(klass, curr_left) {
var left_pos;
left_pos = 0;
$.each($(klass), function(i, el) {
var el_left;
el_left = parseInt($(el).data('left'));
$(el).css({
zIndex: 100 - i
});
if (el_left > curr_left) {
$(el).animate({
left: "-" + left_pos + "px"
}, 100);
left_pos += 100;
}
});
};
I'm not sure what is wrong here. Any thoughts?

Event on margin change

I have an element with animated top margin. I need to detect if it isn't too close from the border, and if it is, scroll parent div to lower position, to prevent animated element from hiding. Here is an example:
http://jsfiddle.net/zYYBR/5/
This green box shouldn't be below the red line after clicking the "down" button.
Do you mean this?
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down').click(function() {
var goStep = step;
var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
if((elHeight + step) > limit)
{
goStep = limit - elHeight;
}
new_margin = goStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({marginTop: new_margin}, 1000);
});
http://jsfiddle.net/zYYBR/8/
EDIT: Or maybe something like that (of course you can improve the calculation, because currently it's very buggy with scroll):
var new_margin;
var step = 75;
$('#down').click(function () {
scroll(1000);
});
var scrollTimer = null;
$("#container").bind("scroll", function () {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () { scroll(1); }, 10);
});
function scroll(speed) {
var scrollStep, animationStep = step;
var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
var nextCurrentBoxBottom = currentBoxBottom + step;
var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop;
if (nextCurrentBoxBottom > limit) {
if (limit >= $("#container")[0].scrollTop) {
scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit;
}
else {
scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit;
animationStep = nextCurrentBoxBottom - limit;
}
$("#container")[0].scrollTop = scrollStep;
}
new_margin = animationStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({ marginTop: new_margin }, speed);
}
http://jsfiddle.net/zYYBR/13/
Do you mean something like this?
I have the same visual result as Alex Dn did, but I added a little extra direction to what I think you're talking about. If it's what you're looking for I'll make updates:
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down2').click(function() {
var anim = $("#animated");
var hrOff = $("#max").offset();
var thOff = anim.offset();
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75);
console.log(new_margin, hrOff.top, thOff.top);
var st = 0;
if (new_margin < 75) {
st = 75 - new_margin;
//have container scroll by this much?
}
anim.animate({
marginTop: "+=" + new_margin
}, 1000);
});​
​
http://jsfiddle.net/zYYBR/10/

Categories

Resources