How to use javascript conditions correctly? - javascript

I have a slider function, which works perfectly fine with moveRight() but I am stuck, and can use it only once.
I decided to use a condition to disable the move function and change the attributes of links on the second click. My code below:
$('#control_next').click(function () {
var used = 0;
if (used == 0) {
moveRight();
used = 1;
} else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
alert(used);
});

You have to place the varaible used outside your event handler because else it will always be 0 with every click:
var used = 0;
$('#control_next').click(function () {
if (used == 0) {
moveRight();
used = 1;
}
else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
alert(used);
});

You should declare variable Globally. Like
var used = 0;
$('#control_next').click(function () {
if (used == 0) {
moveRight();
used = 1;
}
else if (used == 1) {
$('.control_next').attr('href', '#business-events');
$('.control_next').addClass( "url" );
}
});

Related

JS Variable Scope and class change

I have this small little app that I built but I was wondering if there was a way to make this code more condensed/easier
var i = -1;
$( "#next, #back, #remove" ).click(function () {
var filters = [ "aden", "reyes", "perpetua", "inkwell",
"toaster", "walden", "hudson",
"gingham", "mayfair", "lofi",
"xpro2", "1977", "brooklyn"]
function changefilter(){
$('figure').removeClass().addClass(filters[i]);
$('h1').text(filters[i]);
console.log(filters[i]);
}
if (this.id == 'next' && i < filters.length) {
i++;
changefilter();
} else if (this.id == 'back' && i > -1 && i !== undefined) {
i--;
changefilter();} else if (this.id == 'remove'){
i = -1;
changefilter();
}
});
basically the app has 3 buttons which will cycle the class on the figure element.
I am still really new to javascript and I know this would have to do something with the scope but why is it that if I put the "i" variable at the very top (inside) of my function
var i = -1;
$( "#next, #back, #remove" ).click(function () {
var filters = [ "aden", "reyes", "perpetua", "inkwell",
"toaster", "walden", "hudson",
"gingham", "mayfair", "lofi",
"xpro2", "1977", "brooklyn"]
the counter does not move? Also, i put "i" to be -1 because i didn't want to have a class applied until the button was hit. Is this a good way to do this? I also noticed that when pressing the remove button the title stays at the most recent selection and does not revert back to the -1 option
Is there a way to have a variable that all functions, within a function, are able to see without making it global? Is there even a point to doing that? Am I even making sense anymore?
Thanks everyone!
If you want to see this i have a pen at http://codepen.io/Oreilly617/pen/KdrOom
var i = -1;
$( "#next, #back, #remove" ).click(function () {
var filters = [ "aden", "reyes", "perpetua", "inkwell", "toaster", "walden",
"hudson", "gingham", "mayfair", "lofi", "xpro2", "1977", "brooklyn"];
switch (this.id) {
case 'next':
changefilter(++i);
break;
case 'back':
changefilter(--i);
break;
case 'remove':
i = -1;
$('h1').text('Fun Filter');
break;
}
function changefilter(i){
var length = filters.length;
var figure = $('figure');
var current_class = figure.prop('class');
if (i >= 0 && $.inArray(current_class) < (length - 1)) {
figure.removeClass(current_class);
$('figure').addClass(filters[i])
$('h1').text(filters[i]);
}
}
});
I am not sure this meets your "more condensed" but it does resolve the issue of variable scope and demonstrates creation and use of an object to contain functions etc. Some of this is still a bit verbose but left that way for clarity. Note that this also "cycles" through your list and returns back to the base when the next/back reach the end of the cycle as well.
Here is a fiddle if you wish to play around with it: http://jsfiddle.net/MarkSchultheiss/9vzy3rLm/1/
var mything = {
basei: -1,
i: this.basei,
figureSelector: 'figure.lens',
defaultDisplay: 'Fun Filterc',
filters: ["aden", "reyes", "perpetua", "inkwell",
"toaster", "walden", "hudson",
"gingham", "mayfair", "lofi",
"xpro2", "1977", "brooklyn"],
maxFilter: 0,
maxFilterCalc: function () {
this.maxFilter = this.filters.length - 1;
},
changefilter: function changefilter() {
$(this.figureSelector).removeClass(this.filters.join(' ')).addClass(this.filters[this.i]);
if (this.i == -1) {
$('h1').text(this.defaultDisplay);
} else {
$('h1').text(this.filters[this.i]);
}
},
processButton: function (me) {
this.maxFilterCalc();
if (me.id == 'next') {
if (this.i < this.maxFilter) {
this.i++;
} else {
this.i = this.basei;
}
} else if (me.id == 'back') {
if (this.i > this.basei) {
this.i--;
} else {
this.i = this.maxFilter;
}
} else if (me.id == 'remove') {
this.i = this.basei;
}
this.changefilter();
}
};
$("#next, #back, #remove").click(function () {
mything.processButton(this);
});

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

jQuery not responding to timed events

Im having trouble getting my second function to react to the changes the first function brings.
var jumbotron = function(){
var jumbotronCounter = 1
var jumbotronSwitch = function(){
var jumbotronTimer = function(){
jumbotronCounter++
}
jumbotronTimer();
if (jumbotronCounter > 3){
jumbotronCounter = 1
}
console.log(jumbotronCounter);
}
setInterval(jumbotronSwitch,7000);
var jumbotronListener = function(){
if(jumbotronCounter = 1){
console.log('first');
}else if(jumbotronCounter = 2){
console.log('second');
}else if(jumbotronCounter = 3){
console.log('third');
}
};
jumbotronListener();
}
jumbotron();
Id like to use "jumbotronListener" to run some code when "jumbotronCounter" changes
jumbotronListener is indeed only running once. You can, instead, run it every time the interval runs:
var jumbotron = function () {
var jumbotronCounter = 1;
var jumbotronSwitch = function () {
var jumbotronTimer = function () {
jumbotronCounter++;
};
jumbotronTimer();
if (jumbotronCounter > 3) {
jumbotronCounter = 1;
}
// Execute the listener every time the interval runs
jumbotronListener();
console.log(jumbotronCounter);
};
setInterval(jumbotronSwitch, 7000);
// Run for the first time if you wish:
jumbotronListener();
// Set this as function so you can 'use it before declaring it'
function jumbotronListener() {
// You had invalid operators. = assigns and === compares (strictly)
if(jumbotronCounter === 1) {
console.log('first');
} else if(jumbotronCounter === 2) {
console.log('second');
} else if(jumbotronCounter === 3) {
console.log('third');
}
}
};
jumbotron();
You also had some missing semicolons in there, sometimes it's not a problem since JavaScript auto-inserts them, but sometimes it is, so it's a good idea to always make sure to manually insert them where they go.

unbind/turn off a function in jquery

Good day all, I'm trying to make a jquery game where a group of enemy will spawn after a group of enemy gets destroyed. I'm calling alien_cruiser() function & unbinding minion_roulette() function after minion_roulette_counter gets 0. But every time I run, function does not get unbind & after counter gets 0 both type of enemies show. I want to run them one by one. Here are the codes:
var sound = new Audio("sounds//dishoom.ogg");
var score = 0;
var minion_roulette_life = 10;
var cruiser_life = 20;
var minion_roulette_counter = 3;
var cruiser_counter = 3;
function processBullet() {
$(".projectile").each(function() {
var maxTop = $(this).offset().top;
var breakable1 = $(this).collision("#minion-roulette");
var breakable2 = $(this).collision("#cruiser");
$(this).css("top", maxTop - 25);
if (breakable1.length != 0 || breakable2.length != 0) {
$(this).remove();
}
if (maxTop <= 35) {
$(this).remove();
}
if (breakable1.length != 0) {
--minion_roulette_life;
if (minion_roulette_life == 0) {
sound.play();
breakable1.remove();
minion_roulette(true);
minion_roulette_counter--;
$("#score").html(++score);
minion_roulette_life = 10;
}
}
//This is the place where it checks if counter is 0 or not
if (minion_roulette_counter == 0) {
$('#content').unbind(function() {
minion_roulette(false)
});
alien_cruiser(false);
minion_roulette_counter = -1;
}
if (breakable2.length != 0) {
--cruiser_life;
if (cruiser_life == 0) {
sound.play();
breakable2.remove();
alien_cruiser(true);
$("#score").html(++score);
cruiser_life = 20;
}
}
});
}
Am I doing any wrong here? Please I need a solution badly. Tnx.
In this situation, you could use a conditional statement to determine which function to call.
For example:
if (minion_roulette_counter == 0) {
alien_cruiser();
}
else {
minion_roulette();
}
Binding and unbinding doesn't 'turn off' a function, unfortunately. To quote MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
– MDN: 'Bind'

Why are all images be changed to the first input

<script type="text/javascript">
var interval;
$('#105').mouseover(function()
{ mouseOver('105'); });
$('#105').mouseout(function()
{ mouseOut('105') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/268255615/268255615.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/268255615/268255615.1.jpg'); }
</script>
<script type="text/javascript">
var interval;
$('#104').mouseover(function()
{ mouseOver('104'); });
$('#104').mouseout(function()
{ mouseOut('104') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/325082397/325082397.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/325082397/325082397.1.jpg'); }
</script>
The code above is a JavaScript image rotator. The problem with the code is that the last image path always overwrites the image paths before it.
For example if image path one = thumbs/imagea.jpg and if path two = thumbs/imageb.jpg path one ("thumbs/imagea.jpg")then becomes path two on hover becomes ("thumbs/imageb.jpg")
This script worked at one point trying to figure out what is wrong or been changed any ideas?
This is quite obvious: you are redefining mouseOver as a function. The second time you define it, it overwrites the first function. This is because mouseOver is defined on window-scope. Splitting it up in two blocks does not change that. Also note that "interval" is also being defined twice, so a name clash will also occur here.
A solution would be to either use closures, change the name of one of either functions or merge the two functions into one.
Closures are done by wrapping each script in the following block:
(function() {
// your script here
}());
A merged function would be:
var i, setupImage, images;
images = [
{ "id" : "#104", "prefix" : "../thumbs/325082397/325082397." },
{ "id" : "#105", "prefix" : "../thumbs/268255615/268255615." }
];
setupImage = function (image) {
'use strict';
var interval;
$(image.id).mouseover(function () {
var num = 2;
interval = setInterval(function () {
$(image.id).attr('src', image.prefix + num + '.jpg');
if (num === 12) {
num = 1;
} else {
num += 1;
}
}, 500);
});
$(image.id).mouseout(function () {
$(image.id).mouseout(function () {
clearInterval(interval);
$(image.id).attr('src', image.prefix + '1.jpg');
});
});
};
for (i = 0; i < images.length; i += 1) {
setupImage(images[i]);
}

Categories

Resources