These are chat archives for FreeCodeCamp/HelpJavaScript

13th
Aug 2017
Christopher McCormack
@cmccormack
Aug 13 2017 00:22
@luccifer00 don't forget to add jQuery to your codepen
@luccifer00 you should be pulling the value of your search box on click, not when the document loads
luccifer00
@luccifer00
Aug 13 2017 00:24
@cmccormack add jQuery.... very basic... i done it right now thanks
CamperBot
@camperbot
Aug 13 2017 00:24
luccifer00 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1130 | @cmccormack |http://www.freecodecamp.com/cmccormack
Morchid Chellali
@Morched23MJ
Aug 13 2017 00:25
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

channels.forEach(function(item) {
  function api(i) {
    return 'https://wind-bow.gomix.me/twitch-api/streams/' + channels[i] + '?callback=?';
  }
$.getJSON(api(item), function(data) {
  console.log(data);
});
});
Why in the console it tells that it's undefined? the channels[i]?
Christopher McCormack
@cmccormack
Aug 13 2017 00:25
@luccifer00 big help is to check your console in the browser developer tools - first thing I do when anyone has an issue, and in your case it was saying $ not defined or something similar which means jQuery wasn't loaded
luccifer00
@luccifer00
Aug 13 2017 00:26
for the following times i will check the browser developer tolos, and the analize tool from codepen :D
Christopher McCormack
@cmccormack
Aug 13 2017 00:26
@luccifer00 :thumbsup:
@Morched23MJ i is not an index when you pass it to api, it's the channel name
@Morched23MJ try using ...streams/' + i + '?callb... and see if that works
Morchid Chellali
@Morched23MJ
Aug 13 2017 00:28
@cmccormack, worked. Thank you. :)
CamperBot
@camperbot
Aug 13 2017 00:28
morched23mj sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1131 | @cmccormack |http://www.freecodecamp.com/cmccormack
Christopher McCormack
@cmccormack
Aug 13 2017 00:28
@Morched23MJ np
luccifer00
@luccifer00
Aug 13 2017 00:28
i change the var text, from the document loads to the on click.... i belive it dosent matters... @cmccormack
but i still have the same problema... i dont know how to finish my function
Christopher McCormack
@cmccormack
Aug 13 2017 00:30
@luccifer00 codpen seems to be down for me right now... but when I saw your code it looked like all you were doing was showing an empty jumbotron
luccifer00
@luccifer00
Aug 13 2017 00:30
$("#action").on("click",function(){
   var text=document.getElementById("know").value;
  $.ajax( {
    url: 'https://en.wikipedia.org/w/api.php?action=query&titles='+text+'&prop=images&imlimit=20&format=json',
    data: queryData,
    dataType: 'json',
    type: 'POST',
    headers: { 'Api-User-Agent': 'Example/1.0' },
    success: function(data) {
      $("jumbotron").css('visibility','yes');
//i know i have to write here something to get the results and show on the main page...

    } //closing function
  }); //closing ajax
i dont know if i have to follow the same steps as in the quote machin...
i want to use that jumbotron to show the results...
Morchid Chellali
@Morched23MJ
Aug 13 2017 00:32
Is it normal if CodePen is kind of running slow?
luccifer00
@luccifer00
Aug 13 2017 00:32
at this momento i dont know if my Ajax is runing well
Christopher McCormack
@cmccormack
Aug 13 2017 00:32
@Morched23MJ might be having issues at the moment I can't even reach it
@luccifer00 first thing in your ajax success, console.log(data) to make sure you're getting a response!
Morchid Chellali
@Morched23MJ
Aug 13 2017 00:33
I see
Just stopped working lol
luccifer00
@luccifer00
Aug 13 2017 00:33
@Morched23MJ i just have a Windows blue screen while i was on codepen.... something is happening with them
Morchid Chellali
@Morched23MJ
Aug 13 2017 00:33
Unfortunatly. :l
Christopher McCormack
@cmccormack
Aug 13 2017 00:35
@luccifer00 Also - you are using a form - default action for a button in a form is to submit! You need to override this with event.preventDefault():
 $("#action").on("click",function(event){
   event.preventDefault()
luccifer00
@luccifer00
Aug 13 2017 00:36
@cmccormack you probably want to kill me , but... i dont know how to use console.log ..... i write on the place, but i have to review the developer browser to check it??
Christopher McCormack
@cmccormack
Aug 13 2017 00:37
@luccifer00 yes! that's about it!
@luccifer00 super easy, and one of the best tools you have at your disposal
Any time you don't know what's going on, log your variables to console and see if they match what you expect!
luccifer00
@luccifer00
Aug 13 2017 00:40

@cmccormack i will change the event.preventDefault() , but in my mind i want to make:
a form (one place to write what to search)
a button ( i didnt knew a submit button was diferent to a normal button)

and crreate a function for: when the button is clicked, take the text write on the form, and insert on the API url for his search...

Christopher McCormack
@cmccormack
Aug 13 2017 00:40
@luccifer00 in your click handler, it would be very helpful to use something like this:
var text=document.getElementById("know").value;
console.log(text);
luccifer00
@luccifer00
Aug 13 2017 00:40
that was my idea... maybe i so wrong.... lol
Christopher McCormack
@cmccormack
Aug 13 2017 00:41
@luccifer00 that's fine - just know that the job of a form is to submit something to a backend. You are not using a backend, so you need to prevent the default submit action that would send information and then -reload- the page
luccifer00
@luccifer00
Aug 13 2017 00:41
@cmccormack and with console.log(text) i could check it on the developer browser tool
Christopher McCormack
@cmccormack
Aug 13 2017 00:42
@luccifer00 yes! I do this in chrome by right clicking anywhere in the page and clicking inspect but there are keyboard shortcuts as well - I think F12
I'm on a Mac right now can't remember all the shortcuts
luccifer00
@luccifer00
Aug 13 2017 00:43
@cmccormack , what other diferent way to write that is not a form??
Christopher McCormack
@cmccormack
Aug 13 2017 00:43
you can just add items to a <div> instead, no need to be in a form
@luccifer00 if you are controlling everything using javascript you can do anything you want!
luccifer00
@luccifer00
Aug 13 2017 00:44
lol sounds great!! but could be complicate for a begginer like me :D
Christopher McCormack
@cmccormack
Aug 13 2017 00:45
I'm very sorry but I have to go, the Fiancee is ready for dinner!
@luccifer00 not too bad, use that preventDefault and you're already on your way
luccifer00
@luccifer00
Aug 13 2017 00:47
i have homeworks! lol the preventDefault and understanding and the console.log(text) and conole.log(data) for the Ajax, and the most important thing! to understand it! lol
aRtoo
@artoodeeto
Aug 13 2017 00:55
you have any solution other than this?? im really struggling to make less than 5 lines of codes. because of memory that i read. something like that.
function translatePigLatin(str) {
  var vowelsArr = 'aeiou'; //way
  //var constArr = 'BCDFGHJKLMNPQRSTVWXYZ'.toLowerCase(); //ay
  var uno = [];
  var dos = [];
  str = str.split('');

  if (vowelsArr.indexOf(str[0]) === -1) {
    for (var i = 0; i < str.length; i++) {
      if (vowelsArr.indexOf(str[i]) === -1) {
        dos.push(str[i]);
      } else if (vowelsArr.indexOf(str[i]) !== -1) {
        uno.push(str[i]);
        uno = uno.join('');
        dos = dos.join('');

        var newStr = str.splice(0,i);
        console.log(str);
        console.log(newStr);

        return str.join('') + dos + 'ay';
      }
    }
  } else {
    return str.join('') + 'way';
  }
}

//translatePigLatin("consonant");
translatePigLatin("california"); //should return "aliforniacay".
luccifer00
@luccifer00
Aug 13 2017 01:11
@artoodeeto that is a challenge? or something made by you?
aRtoo
@artoodeeto
Aug 13 2017 01:12
@luccifer00 challenge bro. titled pig latin
luccifer00
@luccifer00
Aug 13 2017 01:12
paste the link
@artoodeeto i didnt made it, but we cant try togheter if u want
i pm to you
aRtoo
@artoodeeto
Aug 13 2017 01:15
@luccifer00 i already got the answer. but i want it to be better for sure bro
Diego Mayer
@Chrono79
Aug 13 2017 02:02
@artoodeeto don't use arrays if you don't need to do it
strings have their own indexOf method
Krittiya Clark
@krittiyaclark
Aug 13 2017 02:11
Hi everyone. I am working FCC “Search and Replace”. If I understand the result should be “Search and Replace” and my code has that result but it did not pass. What did I do wrong?
function myReplace(str, before, after) {
  var string = str.split(' ');

for (var i = 0; i < string.length; i++) {
 string.splice(4, 1, after);
 var join = string.join(' ');
  return join;
  //console.log(join);
}

}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Diego Mayer
@Chrono79
Aug 13 2017 02:12
@krittiyaclark why the loop?
and you should keep the same capitalization of the replaced word
Margaret
@Margaret2
Aug 13 2017 02:13
no point to have a loop when you just return on the first run of the loop
Diego Mayer
@Chrono79
Aug 13 2017 02:13
you're hardcoding the replacement there, it'll work only in that case (or another case where the replaced word is the 5th one)
Krittiya Clark
@krittiyaclark
Aug 13 2017 02:15
@Chrono79 So if I use splice() take 'jumped' out and how do I do next?
Diego Mayer
@Chrono79
Aug 13 2017 02:17
@krittiyaclark use replace instead
or if you want to use splice, then use the index of the loop when you find the word and return after the loop
Krittiya Clark
@krittiyaclark
Aug 13 2017 02:23
@Chrono79 I understand a bit. I will try. Thank you.
CamperBot
@camperbot
Aug 13 2017 02:23
krittiyaclark sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4521 | @chrono79 |http://www.freecodecamp.com/chrono79
Tai Jones
@taiJones00
Aug 13 2017 02:24
// Change between F and C when the temp div is clicked
    var change = "F";
    $("#temp").on("click", function() {
      $("#temp").html(tempF + "&deg F");
      if (change == "F")
        {
          change = "C";
        }
      else
        {
          change = "F";
        }
    });
Why can't I change between C&deg and F&deg
Diego Mayer
@Chrono79
Aug 13 2017 02:26
@taiJones00 when you change the html of the #temp, you lose the on click binding maybe?
kumquatfelafel
@kumquatfelafel
Aug 13 2017 02:41
@taiJones00 you might want to also check your conversion formula.
JohuMid
@JohuMid
Aug 13 2017 02:50
Using Objects for Lookups
i need help
kumquatfelafel
@kumquatfelafel
Aug 13 2017 02:51

that's fine.

What have you tried/what are you unsure about?

JohuMid
@JohuMid
Aug 13 2017 02:53
Yes i have
kumquatfelafel
@kumquatfelafel
Aug 13 2017 02:53
That is, post your code
JohuMid
@JohuMid
Aug 13 2017 02:56

var lookup={
'alpha':function(){
return "Adams"; },

 'bravo':function(){

return 'Boston'; },

 "charlie":function(){ 

return "Chicago";},

  "delta":function(){

return "Denver";},

  "echo":function(){

return "Easy"; },

  "foxtrot":function(){ 

return "Frank"; },

"":function(){

return undefined; }

kumquatfelafel
@kumquatfelafel
Aug 13 2017 03:03

Interesting, but not what you want here.
saying lookup['alpha'], for example wouldn't return "Adams". It would give you a function that returns "Adams".
Instead of storing a function as the value of your key value pairs, you just want "Adams" or "Boston" or etc.

e.g. Suppose there was another key "Zed", that I wanted to give me "Zebra"

I wouldn't say "Zed": function blahblahblah

I would say "Zed" : "Zebra"

If I then said lookup["Zed"], this would give me Zebra. From there, I would then need to return that value.

@JohuMid
JohuMid
@JohuMid
Aug 13 2017 03:07
Oh,that's right. Thank you
kumquatfelafel
@kumquatfelafel
Aug 13 2017 03:07
You also don't have to worry about setting up a "return undefined" with objects like that. Calling any key that doesn't exist in lookup will result in an undefined value.
@JohuMid one more thing, check the example to the left, and note that at the end, they use alpha[value]. They want you to recognize you can use val in a similar way.
JohuMid
@JohuMid
Aug 13 2017 03:10
sorry, I ignore it
next time, i will look it up
kumquatfelafel
@kumquatfelafel
Aug 13 2017 03:12
np. Gave me something to do for about ten minutes :)
off for now.
JohuMid
@JohuMid
Aug 13 2017 03:13
srue
Tai Jones
@taiJones00
Aug 13 2017 05:42
function setup() {
  createCanvas(500, 500);
}

function draw() {
  background(51);
}
Does anyone know why this doesn't work
nvm
Pethaf
@Pethaf
Aug 13 2017 06:46
@taiJones00 What does createCanvas do?
zivce_
@zivce
Aug 13 2017 07:14
hey I need some help with cashRegister
How to get Object to 2D array?
Lay
@L-AY
Aug 13 2017 07:33

Hey All,

I noticed multiple web pages use nginx (https://www.nginx.com/resources/wiki/). I used axios (https://github.com/mzabriskie/axios) the other day. Are these similar in their operation/purpose?

One is a web server, the other a HTTP client...could someone please assist in helping me understand more? :smile:
Pieter Stokkink
@forkerino
Aug 13 2017 08:07
@L-AY axios is client-side, you can use it to make HTTP requests to a server. nginx is a server, which can respond to those HTTP requests. They are not interchangable, but complement each other.
Jim Tryon
@jimtryon
Aug 13 2017 08:55
Is anyone around to help with JS?
Johnny
@JohnnyBizzel
Aug 13 2017 09:03
@jimtryon There are always people looking in this room. Ask your question.
Jim Tryon
@jimtryon
Aug 13 2017 09:03
I want to dynamically create a button for each one of the divs on my HTML page, this is what I have so far
Fernando
@lestairon
Aug 13 2017 09:05

Hm, i was doing the challenge https://www.freecodecamp.org/challenges/counting-cards and i tried to do it using only if statements, so far my code is


var count = 0;

function cc(card) {
  // Only change code below this line
  if (card >= 2 || card <= 6) {
    count++;
  }
  else if (card == (10 || "J" || "Q" || "K" || "A")) {
    count--;
  }
  if (count > 0) {
    return count + " Bet";
  }
  else {
    return count + " Hold";
  }
// Only change code above this line
}

// Add/remove calls to test your function.
// Note: Only the last will display
cc(10); cc("J"); cc("Q"); cc('K'); cc('A');

But is not working, do you guys know why?

Jim Tryon
@jimtryon
Aug 13 2017 09:05
function createButton(){
    var divs = $("div");
    var button = $('<input type = "button"')

    for (var i = 0; i < divs.length; i++) {
    divs.appendTo()

}

}
kumquatfelafel
@kumquatfelafel
Aug 13 2017 09:05
@lestairon If you want to do it like that you have to say card == 10 || card == etc.
Fernando
@lestairon
Aug 13 2017 09:07
Oh, i did it
var count = 0;

function cc(card) {
  // Only change code below this line
  if (card >= 2 && card <= 6) {
    count++;
  }
  else if (card >= 7 && card <= 9) {
    count += 0;
  }
  else {
    count--;
  }
  if (count > 0) {
    return count + " Bet";
  }
  else {
    return count + " Hold";
  }
// Only change code above this line
}

// Add/remove calls to test your function.
// Note: Only the last will display
cc(10); cc("J"); cc("Q"); cc('K'); cc('A');
kumquatfelafel
@kumquatfelafel
Aug 13 2017 09:11

@lestairon for future reference, try running this. https://repl.it/KHw4/1

If you use || like you did above, it will grab the first "truthy" value. The comparison operator will not be applied to all of them. It will be applied to the result.

Johnny
@JohnnyBizzel
Aug 13 2017 09:13
@jimtryon this will target all divs var divs = $("div");
Is there an append function in jQuery?
Fernando
@lestairon
Aug 13 2017 09:13
@kumquatfelafel Oh, i thought it was not looping because i gave strings instead of numbers
Thanks, i didn't know that
Jim Tryon
@jimtryon
Aug 13 2017 09:14
@JohnnyBizzel Let me take a look
Johnny
@JohnnyBizzel
Aug 13 2017 09:14
kumquatfelafel
@kumquatfelafel
Aug 13 2017 09:15
@lestairon np... basically, what you had in that if statement was more reminiscent of a switch statement really. You're essentially saying, in all these cases, do this. (which, in case of if, you'd have to apply that comparison operator to each individually)
Jim Tryon
@jimtryon
Aug 13 2017 09:19
@JohnnyBizzel
function createButton() {
    function createButton() {
        /// get the div you want to append and save it to var targetDiv
        var targetDiv = $("div");
        /// looping through the length required
        /// create the button
        /// append the button to the targetDiv
        targetDiv.each(function () {
            var button = $('<input type="submit" name="submit')
            targetDiv.append(button);
        })
        /// end loop
    }
}
Johnny
@JohnnyBizzel
Aug 13 2017 09:19
@jimtryon works?
Jim Tryon
@jimtryon
Aug 13 2017 09:23
No, I’m not calling the function right
     <div class="col col-xs-12 col-md-6 col-lg-4">
            <div>
              <img src="http://lorempixel.com/250/250/">
            </div>
            <h2>Product Name</h2>
            <p>Product Name</p>
            <p>$10.99</p>
            <p>createButton();</p>
          </div>
    function createButton() {
        /// get the div you want to append and save it to var targetDiv
        var targetDiv = $("div");
        /// looping through the length required
        /// create the button
        /// append the button to the targetDiv
        targetDiv.each(function () {
            var button = $('<input type="submit" name="submit"');
            targetDiv.append(button);
        })
        /// end loop
 }
Johnny
@JohnnyBizzel
Aug 13 2017 09:31
@jimtryon You are missing a closing > on the input.
I made this: http://output.jsbin.com/cecineharo
Jim Tryon
@jimtryon
Aug 13 2017 09:33
I’ve modified the function @JohnnyBizzel
function createButton() {
    /// get the div you want to append and save it to var targetDiv
    var targetDiv = $("div");

    /// looping through the length required
    // create the button
    /// append the button to the targetDiv
    targetDiv.each(function () {
        $('<button>', {
            id: 'myCart',
            text: "Add to Cart"
        }).append(targetDiv);
    });
}
using jquery 1.4
Johnny
@JohnnyBizzel
Aug 13 2017 09:38

@jimtryon

    // get the div you want to append and save it to var targetDiv
    var targetDiv = $("div");

You know this is getting all the divs so this comment is not correct.
&...
I don't think this will create a button

        $('<button>', {
            id: 'myCart',
            text: "Add to Cart"
        }).append(targetDiv);
Jim Tryon
@jimtryon
Aug 13 2017 09:38
I want all the divs because I want to dynamically add an "add to cart" button to every div on the page
it’s a shopping cart
that is the syntax I found in jquery 1.4 and stack overflow answer
if I did it right
Johnny
@JohnnyBizzel
Aug 13 2017 09:39
@jimtryon I get that but your comment is wrong.

@jimtryon it should say

get all the divs on the page and save it to var targetDiv (an array)

Jim Tryon
@jimtryon
Aug 13 2017 09:40
oh, I see what you’re saying
Johnny
@JohnnyBizzel
Aug 13 2017 09:50
Jim Tryon
@jimtryon
Aug 13 2017 09:50
that is what I"m trying to do @JohnnyBizzel
oh, so I don’t want to target the div?
Johnny
@JohnnyBizzel
Aug 13 2017 09:51
@jimtryon for var targetDiv = $(".col"); I target the class of the div you want to add a button to.
@jimtryon otherwise you target every div on the page
Jim Tryon
@jimtryon
Aug 13 2017 09:52
ok, I’ll modify my code
Johnny
@JohnnyBizzel
Aug 13 2017 09:53
@jimtryon inside the .each function you can use $(this)
Jim Tryon
@jimtryon
Aug 13 2017 09:53
did you find anything about the jquery 1.4 code?
 $('<button>', {
            id: 'myCart',
            text: 'Add to Cart',
        }).append(targetDiv);
    });
this part?
Johnny
@JohnnyBizzel
Aug 13 2017 09:54
@jimtryon Again, this looks like you are trying to target an element. Just create it as you would any HTML. var button = $('<button id="x" type="button">Add to Cart</input>');
Note id could be created dynamically here.
Jim Tryon
@jimtryon
Aug 13 2017 09:56
Oh, I saw this in a SO answer for how to create an element
Ocean
@UserOcean
Aug 13 2017 09:57
image.png
image.png
Is there any other way to implement this function? I seem to write too complicated.
image.png
Johnny
@JohnnyBizzel
Aug 13 2017 10:03
@jimtryon $("#foo").append("<div>hello world</div>")
Jim Tryon
@jimtryon
Aug 13 2017 10:04
that is the other way I can write it?
Johnny
@JohnnyBizzel
Aug 13 2017 10:04
@jimtryon that was the accepted answer
@UserOcean you can chain functions together.
Jim Tryon
@jimtryon
Aug 13 2017 10:14
It’s not generating the button
function createButton() {
    // target the class of the div to append and save 
    var targetDiv = $(".col");

    /// looping through all the divs and append button to div
    targetDiv.each(function () {
        var button = $('<button id="x" type="button">Add to Cart</input>');
        $(this).append(button);
    });

    createButton();
}
Ocean
@UserOcean
Aug 13 2017 10:40
ok! Let me have try.
Johnny
@JohnnyBizzel
Aug 13 2017 10:42
@jimtryon you should mention a person when chatting. (if you want a quick response).
This is a working version. View source or inspect to see the code.
http://output.jsbin.com/yelatos/1
Jim Tryon
@jimtryon
Aug 13 2017 10:47
@JohnnyBizzel I realized there was a bug in the last version
it was targeting every class with .col including the "Shopping Cart" text
Jim Tryon
@jimtryon
Aug 13 2017 10:57
function createButton() {
    // target the p elemen to append and save
    var targetPara = $("#price");

    var insertElem = $('*:contains("10.99")');

    /// looping through all the divs and append button to div
    targetPara.each(function () {
        var button = $('<input id="x" type="button" value="Add to Cart">');
        insertElem.append(button);
    });
}

createButton();
prakash chandra yadav
@prakashyadav008
Aug 13 2017 10:58
any suggestion
still working on the sky icons though
kumquatfelafel
@kumquatfelafel
Aug 13 2017 11:05
@prakashyadav008 I wouldn't use hover for changing from ºC to ºF.
I'd provide a button or something you could click.
Jim Tryon
@jimtryon
Aug 13 2017 11:27
So I’m trying to build out the shopping cart functionality
function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];

    // add all items to the array of objects
    for (var i = 0; i <= 15; i++) {
        shopItems += i;
    }

    // trigger on the click of the button 
    $(".cart-button").click(function() {
    })

    // add item to shopping cart array
}
any help would be awesome
kumquatfelafel
@kumquatfelafel
Aug 13 2017 11:29
@jimtryon I would maybe avoid giving each button the same exact id. That's asking for problems later if, e.g., you wanted to use getElementById
Jim Tryon
@jimtryon
Aug 13 2017 11:29
where are you referring to @kumquatfelafel?
kumquatfelafel
@kumquatfelafel
Aug 13 2017 11:30
var button = $('<input id="x" type="button" value="Add to Cart">');
Jim Tryon
@jimtryon
Aug 13 2017 11:30
So should I create a separate id for each button?
and append a number?
kumquatfelafel
@kumquatfelafel
Aug 13 2017 11:33
that is option. Again, in the scheme of things, it might not make a difference. But still probably better to be safe than sorry. This way, you nip any potential problem in the bud before it happens.
(and each button having unique id, at end of day, is not the end of world. :p )
kumquatfelafel @kumquatfelafel is away for the time being
Jim Tryon
@jimtryon
Aug 13 2017 11:41
@kumquatfelafel so I modified the function but can’t get the button to load on the page
function createButton() {
    // target the class of the paragraph to append and save 
    var targetElem = $('.cart-button');
    var uniqueId = 0;

    // looping through all the divs and append button to div
    targetElem.each(function () {
        var button = $('<input type="button" value="Add to Cart">');
        button.setAttribute("id", uniqueId);
        $(this).append(button);
    });
}
kumquatfelafel
@kumquatfelafel
Aug 13 2017 11:59
@jimtryon there is, to my knowledge no input of type "button".
Jim Tryon
@jimtryon
Aug 13 2017 11:59
It would have to be submit button
function createButton() {
    // target the class of the paragraph to append and save 
    var targetElem = $('.cart-button');
    var uniqueId = 0;

    // looping through all the divs and append button to div
    targetElem.each(function () {
        var button = $('<input id="" type="submit" value="Add to Cart">');
        button.attr("id", uniqueId);
        $(this).append(button);
    });
}

function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];

    // trigger on the click of the button 
    $(".cart-button").click(function() {
        shopItems.push(this.name);
        shopItems.push(this.price);
    })
}

createButton();

addItems();
Greg Duncan
@GregatGit
Aug 13 2017 12:02
@jimtryon you need to put a debugger; line inside create button and see where it stops and what is working and what isn't
Jim Tryon
@jimtryon
Aug 13 2017 12:02
I printed out console.log(shopItems)
0
:
name
:
"Item name"
price
:
10.99
Fernando
@lestairon
Aug 13 2017 12:04
var myDog = {
  "name": "Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["Free Code Camp Campers"]
};
What's the difference of using quotes on "name", "legs", etc and no using them?
Jim Tryon
@jimtryon
Aug 13 2017 12:09
I can’t get anything to show under shopping cart
function createButton() {
    // target the class of the paragraph to append and save 
    var targetElem = $('.cart-button');
    var uniqueId = 0;

    // looping through all the divs and append button to div
    targetElem.each(function () {
        var button = $('<input id="" type="submit" value="Add to Cart">');
        button.attr("id", uniqueId);
        $(this).append(button);
    });
}

function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];

    // trigger on the click of the button
    $(".cart-button").click(function() {
        var name = shopItems.push(this.name);
        var price = shopItems.push(this.price);

        // show the information on the page
        var targetClass = $('.navbar-brand');
        targetClass.append(name);
        targetClass.append(price);
    })
}

createButton();

addItems();
Stephen James
@sjames1958gm
Aug 13 2017 12:13
@lestairon If the name has no spaces then the quotes are not needed
@jimtryon Does it appear that your page refreshes when you click the button?
@jimtryon Wondering why you made the button type="submit"
Jim Tryon
@jimtryon
Aug 13 2017 12:16
No, it doesn’t seem to refresh
I was thinking an add to cart button would be a submit button
I should check for a refresh now though
It doesn’t appear to refresh
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:17
@jimtryon Don't use setAttribute. Also, you're not actually doing anything to change the value of uniqueId between each created button.
Stephen James
@sjames1958gm
Aug 13 2017 12:17
If you put a console.log in the click handler does it hit it?
Jim Tryon
@jimtryon
Aug 13 2017 12:18
@kumquatfelafel I was using setAttribute to change the id given the uniqueId var
@sjames1958gm I’ll check
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:19
@jimtryon I know. Though see you've already changed it.
Jim Tryon
@jimtryon
Aug 13 2017 12:19
Screen Shot 2017-08-13 at 5.18.47 AM.png
It does
@sjames1958gm
@kumquatfelafel I set it to a default value
@kumquatfelafel and the idea was to change it again to a unique value
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:20
What is this.name, btw?
Jim Tryon
@jimtryon
Aug 13 2017 12:20
my understanding is that this refers to the shopItems array and so I’m accessing the name property of shopItems
but it’s actually undefined so that can’t be right
Stephen James
@sjames1958gm
Aug 13 2017 12:21
@jimtryon .push returns a number - the length of the new array.
You would want one push not two;
var name = this.name;
var price = this.price;
shopItems.push({name, price});
@jimtryon this will be the shopping car element
Jim Tryon
@jimtryon
Aug 13 2017 12:24
function createButton() {
    // target the class of the paragraph to append and save 
    var targetElem = $('.cart-button');
    var uniqueId = 0;

    // looping through all the divs and append button to div
    targetElem.each(function () {
        var button = $('<input id="" type="submit" value="Add to Cart">');
        button.attr("id", uniqueId);
        $(this).append(button);
    });
}

function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];

    // trigger on the click of the button
    $(".cart-button").click(function() {
        console.log("Function reached here");
        var name = this.name;
        var price = this.price;
        shopItems.push(name, price);

        // show the information on the page
        var targetClass = $('.navbar-brand');
        targetClass.append(shopItems);
    })
}

createButton();

addItems();
Let me see if name and price are still undefined
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:25
*shopItems.push({name, price});
Jim Tryon
@jimtryon
Aug 13 2017 12:25
wow,I need to really work on my syntax
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:26
pshaw. Like me, you're just tired. Right? ;)
Jim Tryon
@jimtryon
Aug 13 2017 12:27
yeah, that is part of it
so now I’m doing a debug statement for shopItems
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:27
There's too few hours in day
Jim Tryon
@jimtryon
Aug 13 2017 12:28
that is what I get in the console
Screen Shot 2017-08-13 at 5.27.54 AM.png
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:29

:point_up: August 13, 2017 8:21 AM

Does ... element thingy have a name and a price?

Jim Tryon
@jimtryon
Aug 13 2017 12:30
It has the name "Item name" and price of 10.99
But I’m still not getting anything on the page
For when I print out the shopItems
function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];

    // trigger on the click of the button
    $(".cart-button").click(function() {
        console.log("Function reached here");
        var name = this.name;
        var price = this.price;
        shopItems.push({name, price});
        console.log(shopItems);

        // show the information on the page
        var targetClass = $('.navbar-brand');
        targetClass.append(shopItems);
    })
}

createButton();

addItems();
Stephen James
@sjames1958gm
Aug 13 2017 12:34
@jimtryon Why are you pushing to shopItems, if there is already a value in the array?
this.name and this.price aren't going to give anything because this refers to $('.cart-button')
Also, append expects a HTML element, you are giving it an array
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:34
just to clarify, this does not refer to shopItems. The key to figuring out what's going wrong here is to figure out what, in this case, this refers to. :point_up:
Jim Tryon
@jimtryon
Aug 13 2017 12:36
I want to add the item to the array
which actually means the array should start out empty
Stephen James
@sjames1958gm
Aug 13 2017 12:37
Where is the data going to come from? Is there a form? Or something that has name/price?
Jim Tryon
@jimtryon
Aug 13 2017 12:37
The data is going to come from add to cart button
when I press on add to cart, I want to add that product’s information to an array
so that is where I thought I would use push
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:39
I think @sjames1958gm point is that this product information can't come out of thin air though. It has to be accessible in the click function in some way :point_down:
Stephen James
@sjames1958gm
Aug 13 2017 12:39
That would be '.cart-button' ?
What does that look like in the HTML
Jim Tryon
@jimtryon
Aug 13 2017 12:40
<p class="cart-button"></p>
Stephen James
@sjames1958gm
Aug 13 2017 12:40
@jimtryon So, where are name / price?
Jim Tryon
@jimtryon
Aug 13 2017 12:40
I was trying to think of the simplest way to implement the items
name/price are basically placeholders that I stored in the array
function addItems() {
    const shopItems = [
        {
            name: 'Item name',
            price: 10.99
        },

    ];
Stephen James
@sjames1958gm
Aug 13 2017 12:44
But you want the name/price to come from the DOM? Then get put into that array?
Jim Tryon
@jimtryon
Aug 13 2017 12:44
Yeah, that is what I want
I’m not sure that I captured both of those elements.
This is what that HTML looks like
           <h2>Product Name</h2>
            <p>Product Name</p>
            <p>$10.99</p>
            <p class="cart-button"></p>
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:46
The elements above cart-button are not accessible through cart-button
Stephen James
@sjames1958gm
Aug 13 2017 12:47
Your click handler will have to navigate the DOM to get to those values.
Jim Tryon
@jimtryon
Aug 13 2017 12:47
so I could add a class of name and price on those p elements
I’m not so interested in having all different products as I am in just adding "product name" and 10.99 to the array
Stephen James
@sjames1958gm
Aug 13 2017 12:47
You'd have to go up to the parent of cart-button then find the correct fields.
Jim Tryon
@jimtryon
Aug 13 2017 12:49
I could do var price = $('.cart-button').prev();
Stephen James
@sjames1958gm
Aug 13 2017 12:50
@jimtryon Or in the handler you have $(this).prev(); use this to access the current clicked item
Jim Tryon
@jimtryon
Aug 13 2017 12:51
 // trigger on the click of the button
    $(".cart-button").click(function() {
        console.log("Function reached here");
        var name = this.prev();
        var price = this.prev().prev();
        shopItems.push({name, price});
        console.log(shopItems);

        // show the information on the page
        $('.navbar-brand').append(shopItems);
    })
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:51
I think this would be better. At least, I'm not sure how $('.cart-button') would react when there is more than one cart-button.
Jim Tryon
@jimtryon
Aug 13 2017 12:52
How is that code look?
I used .prev().prev() which not sure if that is a good idea
Stephen James
@sjames1958gm
Aug 13 2017 12:52
@jimtryon you need to use text() to get the contents of the element
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:52
@jimtryon also, is price two or one above?
Jim Tryon
@jimtryon
Aug 13 2017 12:53
@kumquatfelafel price is one above
<div>
              <img src="http://lorempixel.com/250/250/">
            </div>
            <h2>Product Name</h2>
            <p>Product Name</p>
            <p>$10.99</p>
            <p class="cart-button"></p>
          </div>
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:53
@jimtryon You have var price = this.prev().prev();

On the other hand, for name, you just have this.prev();

See where I'm goin' with this? :p

Jim Tryon
@jimtryon
Aug 13 2017 12:55
cart.js:28 Uncaught TypeError: this.prev is not a function
at HTMLParagraphElement.<anonymous> (cart.js:28)
at HTMLParagraphElement.dispatch (jquery-3.2.1.min.js:3)
at HTMLParagraphElement.q.handle (jquery-3.2.1.min.js:3)
Stephen James
@sjames1958gm
Aug 13 2017 12:55
@jimtryon try $(this).prev()
Jim Tryon
@jimtryon
Aug 13 2017 12:56
{name: "Item name", price: 10.99}
1
:
{name: "Product Name", price: "$10.99"}
length
:
2
It looks good, length: 2
Hmm, except I don’t need Item name and Product name
kumquatfelafel
@kumquatfelafel
Aug 13 2017 12:57
Are you saying that you just want price?
Jim Tryon
@jimtryon
Aug 13 2017 12:58
I think I just want the string "Item name" and price
Stephen James
@sjames1958gm
Aug 13 2017 12:59
@jimtryon THen change the HTML where it came from
Make the array empty to start with
kumquatfelafel
@kumquatfelafel
Aug 13 2017 13:00
On verge of passing out, so off for now haha
Jim Tryon
@jimtryon
Aug 13 2017 13:00
Ok, thanks @kumquatfelafel
CamperBot
@camperbot
Aug 13 2017 13:00
jimtryon sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 602 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
Jim Tryon
@jimtryon
Aug 13 2017 13:00
function addItems() {
    // target price and 
    const shopItems = [
        {},

    ];
0: {}
1: {name: "Product Name", price: "$10.99"}
length: 2
That looks right
Stephen James
@sjames1958gm
Aug 13 2017 13:02
@jimtryon empty is [] not [{}]
Jim Tryon
@jimtryon
Aug 13 2017 13:02
Oh, syntax again, damn it
0: { name: "Product Name", price: "$10.99" }
length: 1
The last step is getting this to append to the class element
// show the information on the page
        $('.navbar-brand').append(shopItems);
Stephen James
@sjames1958gm
Aug 13 2017 13:05
@jimtryon You cannot just append an array to the DOM - you will want to build some elements from that
Jim Tryon
@jimtryon
Aug 13 2017 13:09
unction addItems() {
    // target item name and price
    const shopItems = [];

    // trigger on the click of the button
    $(".cart-button").click(function() {
        console.log("Function reached here");
        var name = $(this).prev().prev().text();
        var price = $(this).prev().text();
        shopItems.push({name, price});
        console.log(shopItems);

        // show the information on the page
        var elements = '';
        elements = elements + '<div>'+name+'</div>' + '<div>'+price+'</div>';
        $(".navbar-brand").append(elements);
    })
}
It’s done, thanks a lot @sjames1958gm
CamperBot
@camperbot
Aug 13 2017 13:12
jimtryon sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8307 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Jim Tryon
@jimtryon
Aug 13 2017 13:17
good night guys!
Stephen James
@sjames1958gm
Aug 13 2017 13:18
@jimtryon :+1: :sleeping:
kumquatfelafel
@kumquatfelafel
Aug 13 2017 13:22
@Datikzz what is sum.value, initially?
Ronique Ricketts
@RoniqueRicketts
Aug 13 2017 14:28
anyone has any suggestion as to how to make the computer randomly input values in a space that is not occupied by any content? https://codepen.io/Ronique/pen/EXMRNB
Stephen James
@sjames1958gm
Aug 13 2017 14:37
@RoniqueRicketts compute a random number from 1-9 and if that cell is empty then pick that, otherwise repeat until you find one.
Ronique Ricketts
@RoniqueRicketts
Aug 13 2017 14:38
@sjames1958gm I was trying that and failuing
luccifer00
@luccifer00
Aug 13 2017 14:39

https://codepen.io/luccifer00/pen/YxxjxE

i have some problems with the Ajax code on Wikipedia viewer..... i dont know if i understand the API faq
XMLHttpRequest: Error de red 0x80070005, Acceso denegado (acess denyed)
some help with this please?

Stephen James
@sjames1958gm
Aug 13 2017 14:40
function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1) + myMin); // Change this line
}
let cell;
while (true) {
    cell = randomRange(1, 9) {
   if (cell is empty) break;
}
// cell will be the cell
Just make sure that the board is not full or inifinte loop
Stephen James
@sjames1958gm
Aug 13 2017 14:54
@luccifer00 Not sure what data: is but if you make your url:
url:'https://en.wikipedia.org/w/api.php?action=query&titles='+text+'&prop=images&imlimit=20&format=json&origin=*',
Nazar
@IsaakNazar
Aug 13 2017 15:27
Hello everyone!
first and second jpeg cant load on the page, why?
var maImg = [
        "emma.jpeg",
        "wild.jpeg",
        "kitty.jpeg",
        "island.jpeg"
      ];

      function updateImage(){
        var rand = Math.floor((Math.random() * 3) + 1);
        document.images[0].src = maImg[rand]
      }
      setInterval(updateImage, 2000);
weiruizhang
@weiruizhang
Aug 13 2017 15:39
Because maImg[0] will never appear
Moisés Man
@moigithub
Aug 13 2017 15:46
array index start on 0... if u +1 it never will be 0
should be Math.floor(Math.random()*4) or
Math.floor(Math.random()* maImg.length)
weiruizhang
@weiruizhang
Aug 13 2017 15:48
Suggest the second
Nazar
@IsaakNazar
Aug 13 2017 15:51
function updateImage(){
        var rand = Math.floor(Math.random() * 4);
        document.images[0].src = maImg[rand]
      }

wild.jpeg:1 GET file:///C:/Users/Kyle/Desktop/site/js%20beginning/wild.jpeg net::ERR_FILE_NOT_FOUND
Image (async)
updateImage @ legacy.html:23
setInterval (async)
(anonymous) @ legacy.html:25
emma.jpeg:1 GET file:///C:/Users/Kyle/Desktop/site/js%20beginning/emma.jpeg net::ERR_FILE_NOT_FOUND
I have those jpeg files but somehow cant load
Moisés Man
@moigithub
Aug 13 2017 15:52
file NOT found...
make sure the path/folder match
Nazar
@IsaakNazar
Aug 13 2017 16:01
@moigithub
I upload two another images and change extension from jpeg to jpg
Now it works. Do you know why?
var maImg = [
        "kitty.jpeg",
        "one.jpg",
        "two.jpg",
        "island.jpeg"
      ];
Moisés Man
@moigithub
Aug 13 2017 16:03
nope :)
Nazar
@IsaakNazar
Aug 13 2017 16:05
@moigithub well thanx :) for your help
CamperBot
@camperbot
Aug 13 2017 16:05
isaaknazar sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 3579 | @moigithub |http://www.freecodecamp.com/moigithub
Nazar
@IsaakNazar
Aug 13 2017 16:07
3 month ago here were a lot of campers, but now nobody
Christopher McCormack
@cmccormack
Aug 13 2017 16:46
I believe they removed the link to the chatrooms from the exercises and moved it to the Settings page so not as many people know how to get here
kumquatfelafel
@kumquatfelafel
Aug 13 2017 16:46
@IsaakNazar :point_up: still people, but things seem to have slowed down a bit since got rid of link to here in exercises
Christopher McCormack
@cmccormack
Aug 13 2017 16:46
Haha he posted that 39 min ago and we both respond at the same time
Anyone done d3 within React?
Kelechi Chinaka
@ke1echi
Aug 13 2017 16:47
am having a hard time with nested loops
kumquatfelafel
@kumquatfelafel
Aug 13 2017 16:48
@cmccormack Truth is, I'm not actually here at the moment. I'm really a bot. :o
Christopher McCormack
@cmccormack
Aug 13 2017 16:48
@kumquatfelafel quite self-aware for a bot!
@kelechy what's your roadblock?
Kelechi Chinaka
@ke1echi
Aug 13 2017 16:53
for every iteration of the outter loop, the in loop iterates over all element , right?
Christopher McCormack
@cmccormack
Aug 13 2017 16:59
@kelechy as long as nothing ends the inner loop it should. Something like a return statement in the inner loop will break out of the entire function
Mariusz Klimek
@tarnos12
Aug 13 2017 17:00
Hi
I am trying to do something like this:
var myArray = [
{
width: 100,
x: canvas.width / 2 - this.width / 2
}
]
It is not working tho, since keyword this is a window
Is there a way? or do I need to store my width somewhere else, or instead of object literal I should use a function which will return an object?
Eunice Park
@eunicode
Aug 13 2017 17:04
I have a question about the Search and Replace challenge https://www.freecodecamp.org/challenges/search-and-replace
I'm lost as to why I'm getting this error: TypeError: str.charAt(...).toUppercase is not a function
function myReplace(str, before, after) {

  var position = str.indexOf(before);

  if (str.charAt(position) === str.charAt(position).toUppercase()) {

    var capAfter = after.charAt(0).toUppercase() + after.slice(1);
    return str.replace(before, capAfter);

  } else return str.replace(before,after);

}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Mariusz Klimek
@tarnos12
Aug 13 2017 17:06
try again, perhaps a bug
... Did FCC reset all my challenges? I just checked and my challenges which are 'finished'(greyed out) have no code in them ;(
Christopher McCormack
@cmccormack
Aug 13 2017 17:09
@eunipa toUpperCase() <= notice the C is capitalized
Mariusz Klimek
@tarnos12
Aug 13 2017 17:10
Can someone help me with my problem above(with an object)
Christopher McCormack
@cmccormack
Aug 13 2017 17:10
@tarnos12 you'll have to assign x outside myArray declaration
Mariusz Klimek
@tarnos12
Aug 13 2017 17:11
@cmccormack or width
Christopher McCormack
@cmccormack
Aug 13 2017 17:11
no x as width needs to be defined first
Eunice Park
@eunicode
Aug 13 2017 17:11
@cmccormack wow... /facepalm. Thank you so much!!
CamperBot
@camperbot
Aug 13 2017 17:11
eunipa sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1133 | @cmccormack |http://www.freecodecamp.com/cmccormack
Mariusz Klimek
@tarnos12
Aug 13 2017 17:12
Is there a nice way to do this? I will have more of those objects so creating 20+ variables outside seems wrong
Christopher McCormack
@cmccormack
Aug 13 2017 17:13
@tarnos12
var myArray = [
   {
      width: 100,
   }
]
for (var i =0; i < myArray.length; i++){
   myArray[i].x = canvas.width / 2 - myArray[i].width / 2
}
Something like that maybe
I'm assuming myArray would have more than one object in it, otherwise I don't see why you would need the array
Mariusz Klimek
@tarnos12
Aug 13 2017 17:14

That won't do because the formula might change.

What I am trying to do is to create an array of objects which then I am using to draw borders/menus/buttons etc. on canvas

If there is an efficient way to do that, I could use it :)
For now I will simply hard code width value inside a formula if I cant find a better solution
Christopher McCormack
@cmccormack
Aug 13 2017 17:16
@tarnos12 you can use a function as a property of an object if you want
kumquatfelafel
@kumquatfelafel
Aug 13 2017 17:16
If you're using a formula that might change, you'd need a function. that way can :point_up:
:point_down: (lazy) :laughing:
Christopher McCormack
@cmccormack
Aug 13 2017 17:17
then invoke the function against the other properties of the object in that array index
Mariusz Klimek
@tarnos12
Aug 13 2017 17:17
@cmccormack true, I was thinking of using that, later on when iterating through an array, I will have to check if a property is a function right?
Christopher McCormack
@cmccormack
Aug 13 2017 17:18
@tarnos12 it would be better to use the same schema for all objects. You can use a property like func or whatever then you'll always know func is a function
an array of objects should really have a bunch of similar objects with similar properties
Mariusz Klimek
@tarnos12
Aug 13 2017 17:18
True, I will test that now and see how it is
Christopher McCormack
@cmccormack
Aug 13 2017 17:18
gl
Mariusz Klimek
@tarnos12
Aug 13 2017 17:18
Yes thats what I have :)
Christopher McCormack
@cmccormack
Aug 13 2017 17:18
@kumquatfelafel lol
Mariusz Klimek
@tarnos12
Aug 13 2017 17:18
@cmccormack Thanks
CamperBot
@camperbot
Aug 13 2017 17:18
tarnos12 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1134 | @cmccormack |http://www.freecodecamp.com/cmccormack
Eunice Park
@eunicode
Aug 13 2017 17:19
@tarnos12 If you visit your FCC profile, and click 'view solution' you should be able to see your saved solutions :)
Mariusz Klimek
@tarnos12
Aug 13 2017 17:20
@eunipa I think FCC just lagged, everything is working now :)
Eunice Park
@eunicode
Aug 13 2017 17:21
:thumbsup:
satyendra kr pandit
@satyendra2013
Aug 13 2017 17:33

@satyendra2013
var array=[];
var newArray=[];
function titleCase(str) {
var newStr=str.toLowerCase();
var array=newStr.split(" ");
for(var i=0; i<array.length; i++){
newArray[i]=array[i].charAt(0).toUpperCase()+array[i].substring(1);

}
return newArray.join(" ");
}

titleCase("sHoRt AnD sToUt");
the above code is not fulfilling 3rd case of algorithm challenge
please help?

Stephen James
@sjames1958gm
Aug 13 2017 17:40
@satyendra2013 You should probably not use globals, in general
In this case when I ran your code and moved the globals inside the function it worked.
@satyendra2013 the reason is that newArray doesn't get reset to empty so
"Short And Stout" comes out as Short And Stout Tea Pot
satyendra kr pandit
@satyendra2013
Aug 13 2017 17:46
@sjames1958gm thanks yeah it is working..Thank you
CamperBot
@camperbot
Aug 13 2017 17:46
satyendra2013 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8308 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Mariusz Klimek
@tarnos12
Aug 13 2017 17:48
@cmccormack I know part of this code is pointless since create a method inside an object was sufficient, but I also came with an idea to make a function which returns an object, this allows me to create private variables inside of it which might be helpful at some point.
var PLAYER_BARS = function() {
    var width = 100;
    var height = 30;
    return [
        //health bar full
        {
            w: width,
            h: height,
            type: "health_full",
            getX: function(){
                return canvas.width / 2 - this.w / 2;
            },
            getY: function(){
                return canvas.height - 200;
            },
            color: COLORS.HEALTH_FULL
        },
        //health bar empty
        {
            w: width,
            h: height,
            type: "health_empty",
            getX: function(){
                return canvas.width / 2 - this.w / 2;
            },
            getY: function(){
                return canvas.height - 200;
            },
            color: COLORS.HEALTH_EMPTY
        },
        //speed bar
        {
            w: width,
            h: height,
            type: "speed",
            getX: function(){
                return canvas.width / 2 - this.w / 2;
            },
            getY: function(){
                return canvas.height - 200;
            },
            color: COLORS.SPEED
        },
        //experience bar
        {

        }
    ];
}();
Actually I might pass an argument to this function such as position of a npc and based on that draw health bars
Christopher McCormack
@cmccormack
Aug 13 2017 17:52
@tarnos12 you doing this in vanilla JS?
Mariusz Klimek
@tarnos12
Aug 13 2017 17:52
@cmccormack Yes, why?
Christopher McCormack
@cmccormack
Aug 13 2017 17:52
just curious
Mariusz Klimek
@tarnos12
Aug 13 2017 17:53
I was thinking about using Type/Coffee script which seem to be better, since I have been using Pug for html which uses indents to format the code, what do you think?
I guess typescript is not js :D
or perhaps it is js
Brad
@bradtaniguchi
Aug 13 2017 17:55
typescript is javascript, but with types (seriously)
Christopher McCormack
@cmccormack
Aug 13 2017 17:56
I've been hooked on React for a while now, lets you update stuff like health bars so easily
kumquatfelafel
@kumquatfelafel
Aug 13 2017 17:56
@tarnos12 so... question... are type and color the only key-value pairs that change between objects?
Brad
@bradtaniguchi
Aug 13 2017 17:56
coffeescript is javascript, but with the goal to make things easier to read
Mariusz Klimek
@tarnos12
Aug 13 2017 17:56
@kumquatfelafel yes, I created a constant object to store those values so they can be easly changed from single place
@bradtaniguchi yep I just checked that out, I wasnt sure about typescript, but I knew about coffeescript :D Might give it a try at some point since I like clean code(not that I am good at writing one)
kumquatfelafel
@kumquatfelafel
Aug 13 2017 17:59
k. was gonna say that if making several bars, code along lines of what posted above could result in a lot of repeated code.
Mariusz Klimek
@tarnos12
Aug 13 2017 18:00

@kumquatfelafel I mean, color is using an object:

var COLORS = {
    HEALTH_FULL: "green",
    HEALTH_EMPTY: "red",
    SPEED: "yellow",
    TEXT: "white",
    DEATH: "grey"
};

type is not, I am using it with switch statement, based on that I use different formulas to draw it on the screen since they might be using player/monster stats(such as hp to determine how many % of width I need to draw, thats why I have HP_full and HP_empty

@kumquatfelafel That is true, and I can solve this easly with this function where I can create a single variable that can be reused by multiple bars, this way there wont be much repeated code except for property names
kumquatfelafel
@kumquatfelafel
Aug 13 2017 18:04
aye
Christopher McCormack
@cmccormack
Aug 13 2017 18:04
In React is there a cleaner way to do this? I don't want to use all props for my rect -
  var {fill, height, width, x, y} = props
  var attr = {fill, height, width, x, y}
  return (
    <rect 
        {...attr}
kumquatfelafel
@kumquatfelafel
Aug 13 2017 18:04
off for a while (again)
Christopher McCormack
@cmccormack
Aug 13 2017 18:04
@kumquatfelafel see ya
Moisés Man
@moigithub
Aug 13 2017 18:15
i probably will pass all props and destructure inside rect component @cmccormack
Christopher McCormack
@cmccormack
Aug 13 2017 18:17

@moigithub like

  return (
    <rect 
        {...props}

?

Moisés Man
@moigithub
Aug 13 2017 18:17
y
const Rect = ({fill, height, width=0, x=0, y=0})=>{
  return (....)
}
Christopher McCormack
@cmccormack
Aug 13 2017 18:18
I haven't tried but I would expect errors if the rect didn't have certain attributes included in props
i'll try it now
Moisés Man
@moigithub
Aug 13 2017 18:19
u could set some default values
or set PropTypes validation
Christopher McCormack
@cmccormack
Aug 13 2017 18:20
hmm just tried it and seems to be good, I guess key gets ignored by React which is good, the rest of my props are attributes anyways. Thanks @moigithub !
CamperBot
@camperbot
Aug 13 2017 18:20
cmccormack sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 3580 | @moigithub |http://www.freecodecamp.com/moigithub
RyanHuang06
@RyanHuang06
Aug 13 2017 18:28
I need some help in the challenge "Confirm the ending".
Moisés Man
@moigithub
Aug 13 2017 18:32
show some code and/or explain where u stuck/dont understand helps ... @RyanHuang06
Mariusz Klimek
@tarnos12
Aug 13 2017 18:35

@RyanHuang06
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

"A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence."

You can complete this challenge in 1 line code if you want
Mariusz Klimek
@tarnos12
Aug 13 2017 19:04
console.table(); allows for a nice formatting, my question is how can I edit those values inside a table??(I can see it is not possible but perhaps there is a way)
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:18
ehmmm.. hello , so for the the boo who algorithm.. how is false going to return true ???
like.. its false
korzo
@korzo
Aug 13 2017 19:19
@Kowalatam You can invert boolean value using !
Christopher McCormack
@cmccormack
Aug 13 2017 19:19
@Kowalatam typeof
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:20
ehmmm, i don't get it
i have this code

function booWho(bool) {
  // What is the new fad diet for ghost developers? The Boolean.
  if(bool === true){
    return true;
  } return false;
}

booWho(false);
and everything checks except false
korzo
@korzo
Aug 13 2017 19:21
@Kowalatam You should be checking data type of variable passed to function, not value
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:21
@korzo oohhhh
i see @cmccormack
:smile:
korzo
@korzo
Aug 13 2017 19:22
As @cmccormack wrote, you have to check it with typeof
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:23
thanks @korzo @cmccormack
CamperBot
@camperbot
Aug 13 2017 19:23
kowalatam sends brownie points to @korzo and @cmccormack :sparkles: :thumbsup: :sparkles:
:cookie: 370 | @korzo |http://www.freecodecamp.com/korzo
:star2: 1135 | @cmccormack |http://www.freecodecamp.com/cmccormack
kumquatfelafel
@kumquatfelafel
Aug 13 2017 19:27

@Kowalatam If you wanted to do it in the way you were doing before, btw, you would say

if (bool === true || bool === false)
  return true;
return false;

This works because, remember, === is strict equality.

(which could be simplified to return bool === true || bool === false;)

Mariusz Klimek
@tarnos12
Aug 13 2017 19:28
@kumquatfelafel
if(typeof(bool) === "boolean"){
return true
}
return false
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:28
@kumquatfelafel yeah, cool thanks.. i have used typeof and that worked,,
CamperBot
@camperbot
Aug 13 2017 19:28
kowalatam sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 603 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:29
i didn't actually know they wanted to know if the value was boolean or not
thought they wanted to know if its true or false :)
Mariusz Klimek
@tarnos12
Aug 13 2017 19:29
@Kowalatam they wanted to know if value is primitive boolean or not
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:30
@tarnos12 yeah, i got that now, was thinking the other way before.. english.. :)
is not easy lol
Mariusz Klimek
@tarnos12
Aug 13 2017 19:30
:D
You do know what primitive values are?
0, "", null, undefined, true, false
not sure if I missed something
korzo
@korzo
Aug 13 2017 19:31
@tarnos12 some :)
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:32
yeah, i remember them, probably did'nt remember them]]
Mariusz Klimek
@tarnos12
Aug 13 2017 19:32
Symbol is also a primitive tho I havent used it yet so idk what its for
kumquatfelafel
@kumquatfelafel
Aug 13 2017 19:32
@tarnos12 aware of typeof. Was demonstrating what answer would have looked like following the original logic.
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:32
didn't remember the primitive part
lol
Mariusz Klimek
@tarnos12
Aug 13 2017 19:33
Sometimes its worth reading a challenge few times or go to the "Hint" section and read a bit, there is usually an explanation of what you need to do without giving you an answer(which can also be found if you scroll down a bit)
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:34
yeah,
i searched and didn't see it in the forum @tarnos12
Get Hint button on the left side of the challenge :)
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:36
@tarnos12 ahhh.. never used it before
luccifer00
@luccifer00
Aug 13 2017 19:36

https://codepen.io/luccifer00/pen/YxxjxE?editors=0010

what is wrong in JS fuction? i cant order the (title/content/link) arrays in one element, and créate an other element with other (title/content/link) i use appendChild and append and other stuff and nothing Works... what i am missing???

Elizabeth Paul
@Kowalatam
Aug 13 2017 19:36
i kinda always manually search
lol
Mariusz Klimek
@tarnos12
Aug 13 2017 19:37
@Kowalatam Read-Search-Ask :<
korzo
@korzo
Aug 13 2017 19:38
@luccifer00 .appendChild is for HTML elements
You should use append()
Elizabeth Paul
@Kowalatam
Aug 13 2017 19:38
@tarnos12 thats what i did, i asked here... and i mean, i read it right :)...
Mariusz Klimek
@tarnos12
Aug 13 2017 19:39
@Kowalatam :D
korzo
@korzo
Aug 13 2017 19:39
@luccifer00 Also why assign titles... at every iteration?
luccifer00
@luccifer00
Aug 13 2017 19:41
becouse i want to take title / content/ and link/ for each search ... and make diferents parts...
korzo
@korzo
Aug 13 2017 19:43
@luccifer00
I mean this
      var titles = data[1];
      var resume = data[2];
      var links = data[3];
luccifer00
@luccifer00
Aug 13 2017 19:48

@korzo in my mind i have this.....
make ajax call =>recibed data in array => make loop y for each item from array (ttle, resume and link) créate HTML tag to show
title1
resume1
link1

title2
resume2
link2
.......

that was the idea on my mind....

korzo
@korzo
Aug 13 2017 19:50
@luccifer00 You use appendChild with string. It expect Html Node
@luccifer00 also you have loop inside .text() callback and return nothing, it means it will overwrite #content with empty value
luccifer00
@luccifer00
Aug 13 2017 19:54
that is the question i know i am overwriteing #content, but i would like to créate new elements... and i dont know how ( i dont want to créate diferents div elements) @korzo
korzo
@korzo
Aug 13 2017 19:56
@luccifer00 Collect html output in loop and after loop insert it to #content with .html() method
luccifer00
@luccifer00
Aug 13 2017 19:57
ok! thanks @korzo
CamperBot
@camperbot
Aug 13 2017 19:57
luccifer00 sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
:cookie: 371 | @korzo |http://www.freecodecamp.com/korzo
Jim Tryon
@jimtryon
Aug 13 2017 21:55
I’m trying to get a running total in this function, can you see where I’m going wrong?
function totalCart() {
    var total = 0;

    for (let elem of shopItems) {
        total += shopItems.price(elem);
    }

    console.log(total);
}
korzo
@korzo
Aug 13 2017 22:01
@jimtryon Depends what is shopItems and what is the scope of totalCart
It's better to pass shopItems as parameter
Joseph
@revisualize
Aug 13 2017 22:01
@jimtryon What's the value of shopItems?
@jimtryon Where is the rest of the code?
Jim Tryon
@jimtryon
Aug 13 2017 22:02
const shopItems = [];

function createButton() {
    // target the class of the paragraph to append and save
    var targetElem = $('.cart-button');
    var uniqueId = 0;

    // looping through all the divs and append button to div
    targetElem.each(function () {
        var button = $('<input id="" type="submit" value="Add to Cart">');
        button.attr("id", uniqueId);
        $(this).append(button);
    });
}

function addItems() {

    // trigger on the click of the button
    $(".cart-button").click(function() {
        var name = $(this).prev().prev().text();
        var price = $(this).prev().text();
        shopItems.push({name, price});
        console.log(shopItems[0].price);

        // show the information on the page
        var elements = '';
        elements = elements + '<div>'+name+'</div>' + '<div>'+price+'</div>';
        $('.cart').append(elements);
    })
}

function emptyCart() {
    $('.cart').clear();
}

function totalCart() {
    var total = 0;

    for (let elem of shopItems) {
        total += elem.price;
    }

    console.log(total);
}


createButton();

addItems();

totalCart();
Joseph
@revisualize
Aug 13 2017 22:02
@jimtryon Seriously? you couldn't link to a gist instead?
@jimtryon I'm sorry. I still can't run that code.
Give me something I can run.
korzo
@korzo
Aug 13 2017 22:05
@jimtryon You have different body of function totalCart() in every snippet
korzo
@korzo
Aug 13 2017 22:09
@jimtryon It prints 0$10.99$10.99$10.99 as your price is not numeric
Jim Tryon
@jimtryon
Aug 13 2017 22:19
@korzo thanks, I had to use parseFloat to convert it to numeric
CamperBot
@camperbot
Aug 13 2017 22:19
jimtryon sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
:cookie: 373 | @korzo |http://www.freecodecamp.com/korzo
dyon3334
@dyon3334
Aug 13 2017 22:58
can someone helpe me over here with this code

function chunkArrayInGroups(arr, num) {
  var output = [];
  var index ;
  index = arr.length / num;
  Math.floor(index);
  for (i=0;i<=num;i++){
    for(j=0;j<=index;j++){
   output[i][j].push(arr[i]);
    }
  }
  return output;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);
it only return 0
Joel Y.
@zapcannon99
Aug 13 2017 23:02
I don't think output[i][j] is an array.
@dyon3334 In fact, output[i][j] should do something weird like "can't access something of undefined"
dyon3334
@dyon3334
Aug 13 2017 23:06
@zapcannon99 i dont understand can you explain more please ?
Joel Y.
@zapcannon99
Aug 13 2017 23:07
Sure thing. What I see is output is equal to a blank array
So when you try to access lets say output[0], what would be the result? Nothing, because there is no element 0
What you'll get is undefined
So then what happens when you try to get undefined [j], you'll get an error.
cowCrazy
@cowCrazy
Aug 13 2017 23:08
@dyon3334 you can push() something only to an array, and output[i][j] is not an array, be referencing it like this, JS understands that you are trying to push an element to an array inside an array inside an array
Joel Y.
@zapcannon99
Aug 13 2017 23:09
:point_up:
cowCrazy
@cowCrazy
Aug 13 2017 23:10
@dyon3334 if you wanna add something to output you can simply write output.push()
Joel Y.
@zapcannon99
Aug 13 2017 23:11
Although for your (@dyon3334) purposes, it might not be just output.push(). Just keep that in mind
Stephen James
@sjames1958gm
Aug 13 2017 23:20
@dyon3334 Before you enter the inner loop you need to create an empty array at output[i][j]
Kelechi Chinaka
@ke1echi
Aug 13 2017 23:24
:wave: @sjames1958gm
Stephen James
@sjames1958gm
Aug 13 2017 23:24
@kelechy :wave:
Kelechi Chinaka
@ke1echi
Aug 13 2017 23:25
any ideas how i can format my string?
function repeater(string, n) {
  return string.repeat(1) + " repeated " + n + " times is : " + string.repeat(n)
}
Expected: '"yo" repeated 3 times is: "yoyoyo"', instead got: 'yo repeated 3 times is : yoyoyo'
dyon3334
@dyon3334
Aug 13 2017 23:26
thanks all i was trying in the mean while @zapcannon99 @sjames1958gm @cowCrazy thanks a lot !!
CamperBot
@camperbot
Aug 13 2017 23:27
dyon3334 sends brownie points to @zapcannon99 and @sjames1958gm and @cowcrazy :sparkles: :thumbsup: :sparkles:
:cookie: 329 | @cowcrazy |http://www.freecodecamp.com/cowcrazy
:cookie: 333 | @zapcannon99 |http://www.freecodecamp.com/zapcannon99
:star2: 8309 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Stephen James
@sjames1958gm
Aug 13 2017 23:27
@dyon3334 :+1:
Joel Y.
@zapcannon99
Aug 13 2017 23:27
:thumbsup:
Stephen James
@sjames1958gm
Aug 13 2017 23:28
@kelechy Use template string:
`"${string}" repeated ${n} times is "${string.repeat(n)}"`
Joel Y.
@zapcannon99
Aug 13 2017 23:29
Otherwise you'll need to use \" in the double quotes or have the double quotes in single quotes ' " " '
Kelechi Chinaka
@ke1echi
Aug 13 2017 23:31
ty @sjames1958gm
dyon3334
@dyon3334
Aug 13 2017 23:35
im doing research now about this subject