Archives For javascript

Three different ways to check if an element exists using a selector in jQuery.

if ($("#mydiv").length > 0){
  // do something here
}

if ($("#mydiv").length){
  // do something here
}

if ($("#mydiv")[0]) {
  // do something
}

I want a click event on a div, and it will fire anywhere in the div except for the button inside it.

$(".div").click(function() {
    // Click event for the div, I'm slide toggling something
    alert("clicked div");
});

$(".button").click(function(e) {
     e.stopPropagation();
    // Do stuff for the button click, but don't fire event above
    alert("clicked button");
});

source: Event Order

/*
Michael Le (username: mikele)
Codecademy Answer / Source Code
Object Project
Objects in address books are fun!
*/
var bob = {
    firstName: "Bob",
    lastName: "Jones",
    
    phoneNumber: "(650) 777 - 7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    
    phoneNumber: "(650) 888 - 8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson (person) {
    console.log(person.firstName + " " + person.lastName);
}
//1.4
function list(){
    var numItems=contacts.length;
    for(i=0;i<numItems;i++){
        printPerson(contacts[i]);
    }
}

//1.5
function search(lastName){
    var numItems=contacts.length;
    for(i=0;i<numItems;i++){
        if(contacts[i].lastName===lastName)
            printPerson(contacts[i]);
    }
}

//1.6 function
function add(firstName, lastName, email, telephone){
    //add newPerson object
    var newPerson ={
        firstName: firstName,
        lastName: lastName,
        
        email: email,
        phoneNumber: telephone
    };
    //add object to array
    contacts[contacts.length] = newPerson;
    
}

//1.4 run
list();

//1.5 run
search("Jones");

//1.6 run
add(prompt("first"),prompt("last"),prompt("email"),prompt("tele"));

Javascript has a built in function encodeURIComponent(str) and encodeURI(str) to encode strings into url.

encodeURI()

This function encodes special characters, except: , / ? : @ & = + $ #

var url = "1234 fake street";
url = encodeURI(url);
alert(url); // this prints out "1234%20fake%20street"

encodeURIComponent(str)

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

var url ="san jose, ca";
url = encodeURIComponent(url);
alert(url); // this prints out "san%20jose%C%20ca"

Someone e-mailed and asked for help on this section, so here’s my source code / answer.

Section 1.3: …And the good!

/*
Michael Le (username: mikele)
Codecademy Answers / Source Code
Introduction to Objects:
1.3 Review: ...And the good!
*/
//for loop iterating from 1-20
for(i=1;i<=20;i++){
    
    if(i%3===0){
        //if divisible by 3 and 5 print FizzBuzz
        if(i%5===0)
            console.log("FizzBuzz");
            
        else
            console.log("Fizz");
    }
    else if(i%5===0)
        console.log("Buzz");
    //if not divisible by 3 nor 5 print the number
    else
        console.log(i);
}

1.4 I have to celebrate you baby answer / source code

/*
Michael Le (username: mikele)
Codecademy Answers / Source Code
Javascript Intro to Objects I:
1.4 I have to celebrate you baby.
*/
var getReview = function (movie) {

//use switch statement
switch(movie){
    
    //because you are using RETURN, you do not need BREAK;
    case "Matrix":
        return "good trip out";
    
    case "Princess Bride":
        return "awesome date night movie";
    
    case "Welcome to America":
        return "Amjad's favorite";
    
    case "Remember the Titans":
        return "love the sports";
    
    case "Why do I look like I'm 12?":
        return "The Ryan and Zach Story";
    
    case "Fighting Kangaroos in the wild":
        return "Token Australian movie for Leng";
    
    default:
        return "I don't know!";
    
}
}

Just finished the Blackjack Challenge. Got my cool badge.

Blackjack Badge

Blackjack Badge

/*
Michael Le
Codecademy username: mikele
Javascript Challenge:
Blackjack: Deal 'em Up
*/
// Our deal function will return a random card
var deal = function() {
  card = Math.floor(Math.random()*52+1);
  return card;
};

// Deal out our first hand
var card1 = deal();
var card2 = deal();

// This function takes a card as a parameter and returns 
// the value of that card
var getValue = function(card) {
    // if its a face card, number should be set to 10
    if((card%13===0) || (card%13==11) ||(card%13==12))
        return 10;

    // if its an ace, return 11
    else if(card%13==1)
        return 11;

    // Otherwise number should be set to card modulo 13
    else
        return card % 13;

};

// Score the hand
function score() {
  return getValue(card1) + getValue(card2);
}

console.log("You have cards " + card1 + " and " + card2 +
        " for a score of " + score(card1, card2));
/*
Michael Le
Codecademy username: mikele
Javascript Conditional Project:
One Round of Rock, Paper, Scissors
*/

//empty result string
var result = "";

var player = prompt("Pick rock, paper, or scissors.");

// If the player types "ROCK," the script needs to read 
// that the same as "rock", but only if player !== null!
if(player !==null)
    player=player.toLowerCase();

var choices = ["rock","paper","scissors"];
var computer = choices[Math.floor(Math.random()*3)];

// Rewrite the strings in win, lose, and draw so they contain
// complete sentences stating the result.
var win = "Your "+player+" beats "+computer+". You win.";
var lose = "Your "+player+" loses to "+computer+". You lose.";
var draw = "A draw: "+player+" on "+computer+".";

//conditions of winning and losing
if(player === "rock"){
    if(computer === "scissors"){
        result = win;
    }
    else if(computer === "paper"){
        result = lose;
    }
    else if(computer === "rock"){
        result = draw;
    }
}
else if(player === "paper"){
    if(computer === "rock"){
        result = win;
    }
    else if(computer === "scissors"){
        result = lose;
    }
    else if(computer === "paper"){
        result = draw;
    }
}
else if(player === "scissors"){
    if(computer === "paper"){
        result = win;
    }
    else if(computer === "rock"){
        result = lose;
    }
    else if(computer === "scissors"){
        result = draw;
    }
}

// player clicks cancel, the 'result' should equal "Bye!"
else if(player === null)
    result = "Bye!";
    
// If the player enters any other string, 'result' should 
// equal "I said rock, paper, or scissors!"
else if((player != "rock") || (player != "paper") ||
                            (player != "scissors"))
    result = "I said rock, paper, or scissors!";



console.log(result);
/*
Michael Le
Codecademy username: mikele
Javascript Conditional Project:
The Dice Game
*/

// pick a random number between 1 and 6 for 
//our roll of the die
var die1 = Math.floor(Math.random()*6 + 1);
var die2 = Math.floor(Math.random()*6 + 1);
var score;

// This time if either die roll is 1 then score should be 0 
if(die1==1 || die2==1)
    score = 0;

else {
  // here we need to check if there are doubles.  
  //If so, score should be
  // double the sum of the two dice
  if(die1==die2)
    score = die1*4;
  
  else
    score = die1 + die2;
}

console.log("You rolled a "+die1+" and a "+die2+"
                for a score of "+score);

The Function Project FizzBizz++ full source code from Codecademy. Answered by Mike Le.

/*
Michael Le
Codecademy username: mikele
Javascript Function Project: FizzBuzz++: The Return of Modulus
The Problem
*/

//Create an object called FizzBuzzPlus
var FizzBuzzPlus = {


// return true if the provided value is
// a multiple of 3 or 5 but not both 3 and 5.
// otherwise it returns false

isFizzBuzzie:function(value){
    if((value%3===0 || value%5===0) && 
            !(value%3===0 && value%5===0))
        return true;
    else
        return false;
},

//returns the sum of all the numbers below the maximum 
//provided which are multiples of 3 or 5 but not both

getFizzBuzzSum:function(max){
    var sum=0; 
    for(i=0;i<max;i++){
        //check for 3 or 5 multiples and add to sum
        if(this.isFizzBuzzie(i))
            sum+=i;
    }
    return sum;
},

//returns the count of all the numbers below the maximum 
//provided which are multiples of 3 or 5 but not both

getFizzBuzzCount: function(max){
    var count=0;
    for(i=0;i<max;i++){
        if(this.isFizzBuzzie(i))
            count++; //this means count+1
    }
    return count;
},

//returns the average(sum/count) of all the numbers 
//below the maximum 
//provided which are multiples of 3 or 5 but not both

getFizzBuzzAverage: function(max){
    sum = this.getFizzBuzzSum(max);
    count = this.getFizzBuzzCount(max);
    return sum/count;
}
};

//Complete the answer find for max = 100;
console.log(FizzBuzzPlus.getFizzBuzzAverage(100));

The Function Project FizzBuzz++: The Return of Modulus from Codecademy. Answered by Michael Le.

1.2 Functions: Data Provided / Taken

/*
Michael Le
Codecademy username: mikele
Javascript Function Project: FizzBuzz++: The Return of Modulus
1.2 The Method: Functions: Data Provided / Taken
*/

// Here is our person object
    var person = {
        //giggle
        //returns: 'giggle'
        giggle: function(){
            return "giggle";
        },

        //giggles
        //parameters: n - number of giggles
        //returns: string of giggles of n giggles long
        giggles: function(n){
            if (n>1)
                return this.giggle() + " " 
                         + this.giggles(n-1);
            if (n===1)
                return this.giggle();
        },

        fiveGiggles: function(){
            return this.giggles(5);
        }

    };
    console.log(person.fiveGiggles());

1.7 One More Function

/*
Michael Le
Codecademy username: mikele
Javascript Function Project: FizzBuzz++: The Return of Modulus
1.7 The Method: One More Function
*/

var comedy = {
    
    irony:function(){
        alert("hello");
    },
    
    schadenfreude:function(){
        alert("goodbye");
    },
    
    slapstick:function(n){
        if(n=="Murdoch"||n=="Gates")
            return "Pie!";
        else if(n == "Hollande")
            return "Flour";
        else
            return "Make Up!";
    }
};

//Run each function
comedy.irony();
comedy.schadenfreude();
comedy.slapstick("Gates");