Adding multiple conditions in a function - javascript

I want to add 2 conditions in 1 function but I'm having some problems. The code I'm using is
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos > 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
};
What I want to achieve is that when the video timePos is 1 the video moves up and when the video timePos is 7 goes back to original position.
Any help would be appreciated

First check if timePos is more than 7, and only than if it's more than 1
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos >= 7) {
// move to origin position
} else if (timePos > 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
};

You can use multiple conditions like
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos < 7){
TweenLite.to( videoBGPlayer , 3 , { marginTop: -130 } );
videoBGPlayer.removeEventListener('timeupdate',timeCheck,false);
}
else if (timePos == 7) {
//go back to original position.
}
};

Simple if/else if logic.
if (timePos == 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
else if( timePos == 7){
//Move video down
}
You said when the video's timePos is 1 not greater than 1, if you leave it like this:
if (timePos > 1){
the control will never reach the else if because 7 is greater than 1 so if possible use the equals operator

Something like this?
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos >= 1 && timePos < 7){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}else if(timePos >= 7){
TweenLite.to(videoBGPlayer, 3, { marginTop: 0});
}
};

Related

add multiple numbers to count jquery

this is the dead script for my shooter game (the buttons are just for testing)
but for some reason i cant figure out how to add 10 instead of 1
this is what i have now:
(function(){
const buttons = document.querySelectorAll('.counterBtn')
let count= 0
//Add event listeners and functionailty to each button
buttons.forEach(function(button){
button.addEventListener('click', function(){
//buttons
if (button.classList.contains('-1')){
count--
} else if (button.classList.contains('+1')){
count++
} else if (button.classList.contains('+10')){
}
//Select the counter text
const counter = document.querySelector('#counter')
counter.textContent = count
//dead / alive
if (count <= 0 ){
counter.style.color = 'red'
console.log("dead")
} else if (count > 0){
counter.style.color = 'lightgreen'
console.log("alive")
} else {
counter.style.color = '#000000'
}
if (count <= 0) {
alert ("you died")
} else if (count > 100 ) {
alert ("u r ful health")
} else {
return
}
})
})
})()
can someone please help me?
Use +=, for example:
count += 10
Of course this also works, but is more verbose:
count = count + 10
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment

Trying to debug a custom .sort in a JS array

A link to the Plunker.
I've been working on a button and list system in jQuery for awhile now. Recently I decided to make my code more reproducible. I want to make it so I just have to add classes or IDs, and I don't have to add any additional code. I'm very close to doing that for my entire site. So if you go to this site specifically you will see it in action.
If you click on any buttons, in any order, it will arrange chronologically.
The bugs come from closing them.
If you click at least three, close the middle one, then click a new button, the sort function falls apart and that closed middle one is now floating with the wrong class.
Below is my current jQuery. On my site, ignore the "All Years" button. I'll work on that after I figure out this bug.
//the variables needed for the floating buttons
var groupArray = $(".yearGroup");
var buttonArray = $(".buttonGroup");
var hideGroupArray = $(".hideGroup");
var closeBarArray = $(".closeBar");
var closeBar = $("#allCloseBar");
var allButtonArray = [];
sortElements = function(a,b)
{
if (a.text() < b.text())
{
return -1;
}
else if (a.text() > b.text())
{
return 1;
}
else
{
return 0;
}
}
$.each(buttonArray, function(i, item) {
$(this).click(function(){
console.log($(buttonArray[i]).text())
console.log($(closeBarArray[i]).text())
//for removing the tooltip when the button is clicked. Mostly for Firefox bug
$(".ui-tooltip-content").parents('div').remove();
$(hideGroupArray[i-1]).slideToggle(slideToggleDuration, function(){
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top - 25}, {duration: timeDuration, easing: 'easeOutBack'});
$(buttonArray[i]).toggleClass("float", 1200);
if ($(groupArray[i-1]).height() > 0)
{
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
closeBar.addClass("floatCloseBar");
$(closeBarArray[i]).hide();
allButtonArray.splice(0, 0, $(buttonArray[i]));
var timer;
var delay = 1500;
$(buttonArray[i]).hover(function() {
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
var link = $(groupArray[i-1]);
var offset = link.offset();
var top2 = offset.top;
var left = offset.left;
var bottom = top2 + $(groupArray[i-1]).outerHeight();
//bottom = Math.abs(bottom - offset.top);
var right = $(window).width() - link.width();
right = Math.abs(offset.left - right);
var scrollDuration = 0;
if (inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
//console.log("fast");
scrollDuration = 500;
//$(group).addClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top <= $(groupArray[i-1]).offset().top && allButtonArray.length == 1)
{
//console.log("fast");
scrollDuration = 500;
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 495 && $(buttonArray[i]).offset().top < 1700 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1000;
//console.log("slow");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 1701 && $(buttonArray[i]).offset().top < 3000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1500;
//console.log("slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 3001 && $(buttonArray[i]).offset().top < 6000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2000;
//console.log("much slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 6001 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2500;
console.log("the slowest");
//$(group).removeClass("hoverYear");
}
else
{
scrollDuration = 500;
}
//to prevent the various hover states to take control when the button isn't floating
if (!($(buttonArray[i])).hasClass("float"))
{
scrollDuration = 0;
console.log("doesnt have class")
}
// on mouse in, start a timeout
timer = setTimeout(function() {
//the delay for the hover scroll feature
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top}, scrollDuration, 'easeInOutCubic');
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
$.each(allButtonArray, function(j, val){
$(allButtonArray[j]).appendTo(closeBar);
console.log(allButtonArray.length);
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
//Changes the width of the buttons based upon how many are on the screen
if (allButtonArray.length > 7)
{
$("float").css('width', '7%');
$(val).css('width', '7%');
$(allButtonArray[0]).css('width','7%');
allButtonArray.sort(sortElements);
//console.log(val);
}
else if (allButtonArray.length <= 7)
{
$(val).css("width", '10%');
$("float").css("width", '10%');
allButtonArray.sort(sortElements);
//console.log(val);
}
});
}
if ($(groupArray[i-1]).height() == 0)
{
$(buttonArray[i]).css("width", '50%');
allButtonArray.splice(allButtonArray.indexOf($(buttonArray[i])), 1);
console.log(allButtonArray.length);
$(closeBarArray[i]).show();
$(buttonArray[i]).appendTo($(closeBarArray[i]));
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
}
if (group2001.height() == 0 && group2002.height() == 0 && group2003.height() == 0 && group2004.height() == 0 && group2005.height() == 0 && group2006.height() == 0 && group2007.height() == 0
&& group2008.height() == 0 && group2009.height() == 0 && group2010.height() == 0 && group2011.height() == 0 && group2012.height() == 0)
{
$(closeBarArray[i]).removeClass("floatCloseBar");
htmlBody.animate({scrollTop: revealAllButton.offset().top - 75}, 500);
arrowDown.hide();
arrowUp.hide();
//console.log($(document).height() + " the current height");
}
});
$(buttonArray[i]).toggleClass("openClose");
$(buttonArray[i]).toggleClass("openClose2");
});
});
function inRange(x, min, max){
return (x >= min && x <= max);
}
If you would like a reference to what worked previously, I could post that code. It is much more bulky and much less organized. I've tried many different things to eliminate the bug but I'm at a loss. My knowledge of JS scope is limited.
And thanks for any help, it is very much appreciated.

jquery/javascript errors

does anyone know why the following script is not working.
I'm trying to see if the cookie is set and when it it's i wan't to see if the value is 1 or 0 if the value is 1 i wan't to move my div#content with an offset, but when it's is 0 i want to move it with the same offset, but in the opposit direction
$(function() {
var loc = window.location.pathname.split( '/' );
if("index.php" == loc[3] && (document.cookie('subMenu') === null || document.cookie('subMenu') == 0)) {
document.cookie("subMenu", 1);
animatethis("#content", 1500, "+=50px");
}
else
{
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1)
{
document.cookie("subMenu", 0);
animatethis("#content", 1500, "-=50px");
}
}
});
function animatethis(targetElement, speed, offset) {
var x = $('#menuwrapper').height();
$(targetElement).animate({ marginTop: "+=50"},
{
duration: speed,
});
};
You just don't use your offset variable here :
$(targetElement).animate({ marginTop: "+=50"},
{
duration: speed,
});
Try this :
$(targetElement).animate({ marginTop: offset},
{
duration: speed,
});
You have a syntax error. Missed end of first bracket in following line:
//It would be
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1))
//In place of
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1)

loop start quicker

I would like this function to begin quicker once it ends. Thanks.
demo: http://jsfiddle.net/RuX5d/5/
Here is an actual timing I am currently using: http://jsfiddle.net/RuX5d/51/
$(document).ready(function() {
var i = 1, dir = 1, curFx = 'fadeIn';
var interval = setInterval(function () {
if (i == 6 && $('#slide1').is(':visible')) {
$('#slide1').fadeOut(2000);
return;
}
$('#slide'+ i)[curFx](500);
i = i + 1*dir;
if (i == 10 || i == -1) {
dir = (dir == 1)?-1:1;
curFx = (curFx == 'fadeIn')?'fadeOut':'fadeIn';
}
}, 1000);
});
Change the 500 at the end. It is the number of milliseconds between each executions of the script. Here's a demo: http://jsfiddle.net/RuX5d/49/

Unexpectedly passing integer by reference?

I'm having some issues with this. For some reason, updateCurrentItem is always called with the same parameter regardless.
function updatePromoList(query) {
query = query.toUpperCase();
clearCurrentList();
var numItems = 0;
currentItem = 0;
result_set = cached[query.charAt(0)][query.charAt(1)][query.charAt(2)];
for(i in result_set){
if(numItems >= NUMBER_MATCHES){
$("<li/>").html("<span style='color: #aaa'>Please try to limit your search results</span>").appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(numItems+1); });
break;
}
promo = result_set[i];
found_number = false;
if (!promo.client)
found_number = (promo.prj_number.toString().substr(0,query.length) == query) ? true : false;
if (query.length >= MATCH_NAME) {
if(promo.prj_name && typeof promo.prj_name == 'string'){
found_name = promo.prj_name.toUpperCase().indexOf(query);
} else {
found_name = -1;
}
if (promo.client)
found_client = promo.client_name.toString().indexOf(query);
else
found_client = -1;
} else {
found_name = -1;
found_client = -1;
}
if(found_client >= 0) {
var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.client_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); }); } else if(found_name >= 0 || found_number) { var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.prj_number+": "+promo.prj_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); });
}
if(found_number || found_client >= 0 || found_name >= 0){
numItems++;
}
}
}
function updateCurrentItem(i){
currentItem = i;
console.log("updating to", i);
}
The results of running this are:
setting 0
setting 1
setting 2
setting 3
setting 4
setting 5
setting 6
setting 7
setting 8
setting 9
setting 10
setting 11
setting 12
setting 13
then when I move my mouse over the content area containing these <li>s with the mouseOver events, all I ever see is:
updating to 4
Always 4. Any ideas?
You're creating a closure but it's still bound to the numItems variable:
function(event){ updateCurrentItem(numItems+1); }
What you should do is something like this:
(function(numItems){return function(event){ updateCurrentItem(numItems+1); }})(numItems)
Edit: I think I might have the wrong function but the same principle applies:
function(event){ updateCurrentItem(thisIndex); }
should be
(function(thisIndex)
{
return function(event){ updateCurrentItem(thisIndex); }
})(thisIndex)

Categories