Syntax or logical error in jquery/javascript - javascript

I have a variable number of promotional items (panels) that are in a sliding belt, that should be set to the width of a panel (300px) multiplied with the amount of panels.
It alerts the correct beltsize. With fixed numbers the slider works too. I suspect the error to be in the if/else if part. I am not even sure this is valid Javascript Syntax.
Any hint is appreciated.
$(window).ready(function(){
var whichpanel = 1;
var panels = $(".panel").length;
var beltsize = panels*300;
$('.belt').css({'width':beltsize});
});
$(window).ready(function promoslider(){
if (panels>whichpanel){
$('.belt').delay(7000).animate({'left':'-=300'}, 500);
whichpanel += 1;
}
else if (panels=whichpanel){
$('.belt').delay(7000).animate({'left':'0'}, 500);
whichpanel = 1;
}
setTimeout(promoslider, 0);
});
promoslider;
UPDATE! Here is the code that works for me now (http://jsfiddle.net/zr5Nd/10/):
$(window).ready(function () {
var whichpanel = 1;
var panels = $(".panel").length;
var beltsize = panels * 300;
$('.belt').css({
'width': beltsize
});
function movingdiv() {
if (panels > whichpanel) {
//alert('Panels:' + panels + '/whichpanel:' + whichpanel);
$('.belt').delay(1000).animate({
'margin-left': '-=300px'
}, 500);
whichpanel += 1;
} else if (panels == whichpanel) {
//alert('Panels:' + panels + '/whichpanel:' + whichpanel);
$('.belt').delay(1000).animate({
'margin-left': '0'
}, 500*panels);
whichpanel = 1;
} else {
alert('3');
}
setTimeout(movingdiv, 0);
}
setTimeout(movingdiv, 0);
});

You need to use the equality/identity operators (==/===) instead of the assignment operator = in your else if statement, e.g.
else if (panels == whichpanel){
$('.belt').delay(7000).animate({'left':'0'}, 500);
whichpanel = 1;
}
Also, I believe promoslider; is supposed to be promoslider();.

You should put the call of promoslider into $(window).ready as well, as the function does not yet exist otherwise. Plus you have to do the call this way promoslider(), promoslider alone will not result in a call.
And of course you have to use the equals-operator == instead of the assign-operator = in your if else-statement.

use panels === whichpanel instead of panels=whichpanel
variables whichpanel, panels have lost their scope in the if/else if part.

Related

Boolean logic misunderstanding

I'm having a problem here. In the beginning of my game it asks "Ready" and if you click it, it will reset everything just in case the game glitched out and it would play the appropriate level that the user selected in the beginning of the game (main menu). I tried to make booleans for each level so I could tell what level he or she is playing this is what I tried and received no luck.
var playingLevel1 = false;
var playingLevel2 = false;
$('#level1Button').click(function() {
playingLevel1 = true;
});
$('#level2Button').click(function() {
playingLevel2 = true;
});
$('#ready').click(function() {
if(playingLvl2) {
startLvl1(); //and that would reset and start the level one
}
if(playingLvl2) {
startLvl2(); //and that would reset and start the level two
}
});
You would think that would work? But it doesn't. I don't think I'm using booleans right maybe?
I just typed up that sample code but it's pretty identical to what my original code is like.
Ok so I decided to use an integer but that still wont work here is what i got
var currentLevel = 0;
$('#level1').click(function () {
currentLevel = 1;
$("#mainMenu").hide();
levelOne();
});
$('#level2').click(function () {
currentLevel = 2;
$("#mainMenu").hide();
levelTwo();
});
function startLvl1() {
$("#levelOne").css('margin-top', '-1520px');
$("#player").css('border', 'solid 1px green');
$("#player").css('margin-left', '223px');
$('#levelComplete').hide();
$('#levelOne').animate({
'margin-top': '+=1520px'
}, speed);
handleCollisions();
}
function startLvl2() {
$("#levelOne").css('margin-top', '-4560px');
$("#player").css('border', 'solid 1px green');
$("#player").css('margin-left', '223px');
$('#levelComplete').hide();
$('#levelOne').animate({
'margin-top': '+=4560px'
}, speed);
handleCollisions();
}
$('#yes').click(function () {
if (currentLevel == 1) {
startLvl1();
}else if (currentLevel == 2) {
startLvl2();
}
Instead of using Boolean, consider storing integer of the level number.
var currentLevel = 0;
$('#level1Button').click(function() {
currentLevel = 1;
});
$('#level2Button').click(function() {
currentLevel = 2;
});
$('#ready').click(function() {
if (currentLevel == 1)
startLvl1();
else if (currentLevel == 2)
startLvl2();
});
This should be the right way! :)
The boolean variables are misspelled? I.e., 'playingLevel1' is the variable defined, but your if statement has 'playingLvl1'. So, since that variable is not defined, it is always false. Same goes for 'playingLevel2'.

Show more/less items using jQuery

I've got a set of elements and I don't want to show them all at once.
My problem is that I've got to use this a series of times in the same page.
Do you guys know jQuery plugin that does what I've written?
jQuery(function($) {
$lis = $('.addfilter');
min = 2;
max = $lis.length;
var visible = min;
function showUpToIndex(index) {
$lis.hide();
$lis.slice(0, index).show();
}
function disableButtons(){
if (visible >= max){
visible = max;
$('#more').hide();
}
else
{
$('#more').show();
}
if (visible <= min){
visible = min;
$('#less').hide();
}
else
{
$('#less').show();
}
}
showUpToIndex(visible);
disableButtons();
$('#more').click(function(e) {
e.preventDefault();
visible = visible + 5;
disableButtons();
showUpToIndex(visible);
});
$('#less').click(function(e) {
e.preventDefault();
visible = visible - 5;
disableButtons();
showUpToIndex(visible);
});
});
Here is a working example:
http://jsfiddle.net/cUUfS/179/
Thanks!
Please try these,
http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/
https://github.com/mfarid/readmore-readless
This may help I hope

clearInterval() not working

SYNTAX ERRORS FIXED. Dreamweaver says that I have an error in my code on line 52. I can't see what is wrong? Maybe this has something to do with the fact that my if and else statements are not working.
IF AND ELSE STATEMENTS FIXED. If I test the if and else statements individually they work correctly, but when I run the entire document, they do not run. Could someone tell me if the error and my if/else statements not working are related or if there is something else wrong.
<script>
var car1=new Object();
car1.Name="Rusty";
car1.Speed="1px", 40;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed="2px", 40;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed="4px", 40;
car3.Distance=0;
function runRusty(){
setInterval(function(){moveRusty()},40);
function moveRusty(){car1.Distance=car1.Distance +1
document.getElementById("rusty").style.marginLeft=car1.Distance + "px"
};
};
function runDusty(){
setInterval(function(){moveDusty()},40);
function moveDusty(){car2.Distance=car2.Distance +1
document.getElementById("dusty").style.marginLeft=car2.Distance + "px"
};
};
function runCrankshaft(){
setInterval(function(){moveCrank()},40);
function moveCrank(){car3.Distance=car3.Distance +1
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px"
};
};
function winLose () {if (document.getElementById("rusty").style.marginLeft="900px"){
alert("Winner is Rusty!");
clearInterval(runRusty);
}
else if(document.getElementById("dusty").style.marginLeft="900px"){
alert("Winner is Dusty!");
clearInterval(runDusty);
}
else if(document.getElementById("crankshaft").style.marginLeft="900px"){
alert("Winner is Crankshaft!");
clearInterval(runCrankshaft);
};
};
</script>
EDIT:
The if and else statements now work as I changed declared my functions globally and changed them slightly. The code now looks as such:
var car1=new Object();
car1.Name="Rusty";
car1.Speed=1;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed=2;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed=4;
car3.Distance=0;
var moveRusty;
var moveDusty;
var moveCrankShaft;
function runRusty(){
moveRusty=setInterval(function(){
car1.Distance=car1.Distance + car1.Speed;
document.getElementById("rusty").style.marginLeft=car1.Distance + "px";
winLose();
},40);
};
function runDusty(){
moveDusty=setInterval(function(){
car2.Distance=car2.Distance + car2.Speed;
document.getElementById("dusty").style.marginLeft=car2.Distance + "px";
winLose();
},40);
};
function runCrankshaft(){
moveCrankShaft=setInterval(function(){
car3.Distance=car3.Distance + car3.Speed;
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px";
winLose();
},40);
}
function winLose () {
if (car1.Distance >= 900){
alert("Winner is Rusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car2.Distance >= 900){
alert("Winner is Dusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car3.Distance >= 900){
alert("Winner is Crankshaft!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
};
clearInterval(moveRusty);
clearInterval(moveDusty);
clearInterval(moveCrankShaft);
Everything works now. All the alerts happen and the position of the cars is reset. But all my clearInterval() do not work. I don't know if clearInterval() is the correct thing to use. What I want to do is reset the page so that I can run the "game" again. Right now, the only way to do that is by refreshing the page. I've double checked how I've declared my setInterval() and how I'm calling them in my clearInterval(), and as far as I can it's right?
You are using clearInterval() wrong. You are passing it a function parameter whereas it expects an object.
// correct usage
var time = setInterval(stuff, 100);
clearInterval(time);
You have a semi colon before the else. ; which is a syntax error, remove it . You have a lot of them in weird places also, I suggest you don't put them after function declarations, if blocks if/else blocks, loop blocks etc.
When you want to test if to things are 'equal' in a if statement, you need to use == or === and NOT =
if (document.getElementById("crankshaft").style.marginLeft = "900px") // WRONG
if (document.getElementById("crankshaft").style.marginLeft == "900px") // RIGHT
if (document.getElementById("crankshaft").style.marginLeft === "900px") // BETTER
Read the answer to the following question to know the difference between == and ===
Difference between == and === in JavaScript
Hope this helps

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.

Mootools Javascript can't push to array

I have an array set with the heights of each hidden div, but when I use it, the div instantly jumps down, rather than slowly sliding as when there is a literal number.
EDIT: testing seems to reveal that it's a problem with the push method, as content_height.push(item.getElement('.moreInfo').offsetHeight);alert(content_height[i]);gives undefined, but alert(item.getElement('.moreInfo').offsetHeight); gives the correct values
Javascript:
window.addEvent('domready', function(){
var content_height = [];i=0;
$$( '.bio_accordion' ).each(function(item){
i++;
content_height.push( item.getElement('.moreInfo').offsetHeight);
var thisSlider = new Fx.Slide( item.getElement( '.moreInfo' ), { mode: 'horizontal' } );
thisSlider.hide();
item.getElement('.moreInfo').set('tween').tween('height', '0px');
var morph = new Fx.Morph(item.getElement( '.divToggle' ));
var selected = 0;
item.getElement( '.divToggle' ).addEvents({
'mouseenter': function(){
if(!selected) this.morph('.div_highlight');
},
'mouseleave': function(){
if(!selected) {
this.morph('.divToggle');
}
},
'click': function(){
if (!selected){
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
item.getElement('.moreInfo').set('tween', {
duration: 1500,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', content_height[i]); //replacing this with '650' keeps it smooth
selected = 1;
thisSlider.slideIn();
}
else{
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
thisSlider.slideOut();
item.getElement('.moreInfo').set('tween', {
duration: 1000,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', '0px');
selected = 0;
}
}
});
} );
});
Why could this be? Thanks so much!
There's nothing wrong with your code. The push method works as expected - here's an example: http://jsfiddle.net/oskar/D2xps/
You need content_height[i - 1].
Also I'd recomend you use another indexing (since your code using global variable 'i' and it could fail because of closures):
$$( '.bio_accordion' ).each(function(item, index) {
content_height[index] = item.getElement('.moreInfo').offsetHeight;
....
tween('height', content_height[index]);
});

Categories