I'm trying to have a balance go up if the function "neww" is true, and down if false. neww is a random number from 0-1:
Template.result.helpers({
'neww': function(){
return( Session.get('number') > 0.5 ? true : false )
}
});
so this should declare new true or false based on the randomly generated number right? Well, I have an if else statement like this:
Template.balance.events({
'click button': function() {
if (neww = true) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
It should raise my balance 1 if the number is greater than .5 and lower it otherwise.
My entire code is:
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('number', Random.fraction());
Session.setDefault('word', "");
Session.setDefault('bal', 5000);
Template.hello.helpers({
number: function () {
return Session.get('number');
}
});
Template.balance.helpers({
bal: function () {
return Session.get('bal');
}
});
Template.hello.helpers({
word: function () {
return Session.get('word');
}
});
Template.hello.events({
'click button': function () {
// increment the counter when button is clicked
Session.set("number", 0+Random.fraction());
}
});
Template.result.helpers({
'neww': function(){
return( Session.get('number') > 0.5 ? true : false )
}
});
Template.balance.events({
'click button': function() {
if (neww = true) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
Any help or tips would be appreciated.
neww, like all helpers, is only available within your templates themselves. If you want to use it in your JS, just make it a normal JS function and call it as normal. You can assign that function to a helper as well if you want to use it in templates too.
At present, neww will be undefined in the context you're trying to use it, so you should see errors in your console when you click the button. The function will throw before it actually does anything, which is why nothing's happening to the balance.
This is not the correct syntax for if
if (neww = true)
neww is not variable, it is a helper, thus you cannot make it in the if like that. In order to let neww is available on the balance template, you need to save it into a global variable like Session
I know that you are new to coding, therefore, learn about basic programming first. Working with frameworks like meteor straight away will make you feel bored gradually
Here's how you can fix the code to make it do what you want:
Template.balance.events({
'click button': function() {
if ( Session.get('number') > 0.5 ) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
You can completely get rid of your neww helper. To read more about how template helpers, events, and sessions work, checkout the Meteor Guide.
Related
I am trying to make a when statement but it is not working as planned. Basically its a function to call another function when try. First before I explain further here is the syntax
when(function() {
//code here
});
Now basically... Think this way.. We have a progressbar.. We also have a custom event such as...
var pBarEvent = document.createEvent('Event');
pBarEvent.initEvent('pbardone', true, true);
document.addEventListener('pbardone', function() {
//code here
});
//if progress bar reaches 100 dispatchEvent
if (document.querySelector(".progress-bar").style.width === 100 + "%")
{
document.dispatchEvent(pBarEvent);
}
Now that piece of code is an example. If the document loads and its for instance at 50% it wont trigger until you add another event such as keydown or click. I dont want to do that I want to do.... "when" progress bar width equals 100% trigger it. Thats basically what needs to happen. So here is the code for the when statement so far (keep in mind its not the best looking one. As I dont normally do this but I wanted to keep this dynamic and who knows someone who later wants to do this can look at this question)
when function
function when(func)
{
var nowActive = false;
if (!typeof func === 'undefined')
{
func = new Function();
}
if (func)
{
nowActive = true;
clearInterval(whenStatementTimer);
}
else
{
nowActive = false;
var whenStatementTimer = setInterval(function() {
switch(func)
{
case true:
{
nowActive = true;
when();
break;
}
case false:
{
nowActive = false;
when();
break;
}
}
}, 1000);
}
if (nowActive === true)
{
func();
}
}
Now this does not work when I go to try something like....
when(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("100%");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style("body", "background", "black");
});
});
It does not trigger. I need help possibly getting this when statement to work. What am I doing wrong? What can I do to fix it? No errors get thrown but it never fires.
edit based on answer
Function tried
function when(currentValue)
{
try
{
var o = {};
o.currentValue = currentValue;
o.do = function(func)
{
if (!typeof func === 'undefined')
{
func = new Function();
}
if (this.currentValue)
{
func();
}
else
{
setTimeout(this.do(func), 100);
}
};
return o;
}
catch(e)
{
console.log(e);
}
}
used as
when(true).do(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
});
This does not work. It never fires. But if I use a onclick listener as such it fires
document.addEventListener("click", function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
}, false);
function when(statement){
o={};
o.statement=statement;
o.do=function(func){
awhen(this.statement,func);
};
return o;
}
function awhen(statement,func){
if(eval(statement)){
func();
}else{
window.setTimeout(function(){awhen(statement,func);},100);
}
}
Use:
when("true").do(function(){});
It works now :) . Its important to put the condition in ""!
I have a Jquery animation that is running the code from its function before the animation is complete. the Page this code is being used at is no where near complete yet but if you want to take a look it's cottageboards.com/orderform
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').attr('src', selectedimg).load(function () {
$('#largeImage').fadeIn(1000, function () {
//Everything below here is running before the above image's fade in is complete
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
});
});
});
When rewritten so the load function comes before the src change it works like a charm. Thanks for the help guys!
Working code:
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').unbind().load(function () {
$('#largeImage').fadeIn(1000, function () {
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
}).attr('src', selectedimg);
});
});
You are binding the load function to largeimage every time you click. The first click the load function gets called once, the second time, it gets called twice. I suspect everything is getting messed up because you are firing multiple .fadeIns on the same object, and they are running in parallel.
Only call $('#largeImage').load(...) once, not on every click. Of course, you'll have to do something about your captured vars, but that's a different issue. Alternatively, call $('#largeImage').unbind().load(...)
If that's hard to follow, replace this line:
$('#largeImage').attr('src', selectedimg).load(function () {
with:
$('#largeImage').unbind().attr('src', selectedimg).load(function () {
I tested it by putting a break point after this line:
$('#thumbs').delegate('img','click', function() {
and calling $('#largeImage').unbind(); and everything seemed to work, so you can do it that way too.
see this fiddle for example how to use done : http://jsfiddle.net/gcnes8b2/1/
$('span').click(function() {
$('#1').fadeIn({
duration: 1000,
done:function(){
$('#2').fadeOut(1000);
// etc
}
});
});
I have a simple jquery-ui slider which I am continuously automatically looping through values. I successfully have a button which starts the movement, but I forget how I can pause/stop the movement when another button is pressed? I know this is something really simple, but am having an absolute mind blank and google is not giving me what I want. (probably because i'm searching for the wrong wording). What can do I put in the pauseSlider function to ... pause the slider!
function scrollSlider() {
var slideValue;
slideValue = $("#slider").slider("value");
if (slideValue >= 0) {
if (slideValue == 2013) {
slideValue = -1;
}
$("#slider").slider("value", slideValue + 1);
console.log($("#slider").slider("value"));
setTimeout(scrollSlider, 1000);
}
}
$('#startSlider').click(function() {
scrollSlider();
});
$('#pauseSlider').click(function() {
//What do I put in here?
});
setTimeout returns a random number which you'll have to store in a variable and then use it to clear the setTimeout in $('#pauseSlider')'s click handler.
var id;
function scrollSlider() {
// (...) code
id = setTimeout(scrollSlider, 1000);
// (...) more code
}
$('#pauseSlider').click(function() {
clearTimeout(id);
});
I have the following code which changes the text in a certain element on click depending on the text value present in the element at the time the event is fired.
http://jsfiddle.net/TNDhL/
$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
Please see fiddle above for working version.
I'd like to find a way to make this more manageable in order to make extending this further easier. Is there a better way to handle this case? Condensing this into a function and using variables to store the value of #textContainer would be more ideal. Any suggestions?
Seems like a perfect case for a closure which can track your progress with a simple counter.. Could look something like this:
var myTextRotator = (function () {
var myPhraseArray = ["first phrase", "second phrase"],
counter = 0;
return {
clickLeft: function () {
counter -= 1;
return myPhraseArray[counter]; //return array item or do your processing here
},
clickRight: function () {
counter += 1;
return myPhraseArray[counter]; //return array item or do your processing here
}
};
}());
Tie the clickLeft and clickRight methods to an jQuery .on(). May have to add a conditional in there so the counter doesn't go below 0 or above the array length.
You would use this like:
$(".left").on("click", function () {
myTextRotator.clickLeft();
});
$(".right").on("click", function () {
myTextRotator.clickRight();
});
I'm not too sure what's going on here and feel I may be missing something that is probably quite obvious, but I have an if else in which both statements are being called. If someone could shed some light on this that would be great. The code below is using asual and should be detecting whether or not a div $('#' + $.address.hash() has already been loaded. However both if and else events are being fired in order. In fact the else statement fires twice...
$('#lmit_back').show(400, function() {
if($('#' + $.address.hash() ).length == 0) {
$('#init').load('inithandler.php', { 'address' : $.address.hash() }, function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else {
alert('hey');
}
});
Here is all the code..I can't really work out what could cause it to execute twice, unless it has something to do with address.change which im not as familiar with as I would like to be.
if (($.address.hash() == '')) {$.address.hash('home');}
$('#lmit_back').click(function() {
$.address.hash('home');
});
$.address.change( function() {
if (!($.address.hash() == 'home'))
{
var exception = '.' + $('[href="#' + $.address.hash() + '"]').parent().attr('class');
$('#left_menu_bar li:not(' + exception + ')').hide(300,function() {
$(exception).show( function() {
$('#left_menu_bar').animate({ width:'100%'},400, function() {
$('#lmit_back').show(400, function() {
if ($('#' + $.address.hash() ).length === 0)
{
$('#init').load('inithandler.php', { 'address' : $.address.hash() } , function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else
{
alert('nigs');
}
});
});
});
});
}
else
{
$('#left_menu_bar').animate({ width:'251px'}, function() {
$('#left_menu_bar li').show( function() {
$('#lmit_back').hide();
});
});
$('#left_menu_bar').css('width','251px');
}
});
The problem here is not arising from the code you have pasted. The only way the code could be running multiple times and hitting multiple branches is if it is being executed more than once. Look to the surrounding code for places where this could be called more than once.
I faced similar issue, while debugging when if condition was true it also went in else block. Later I added alert and console.log in if/else block's & realized, else was not actually being executed but while debugging it looked like it was in else.
So, whoever faces same issue verify by adding alert or console.log.
I was seeing the same behavior, when I debugged step by step it worked. It ended up being that I was attaching multiple click events so the code fired n times.