Skip to content

Instantly share code, notes, and snippets.

@coopermayne
Last active October 22, 2015 13:46
Show Gist options
  • Save coopermayne/1865d17c56c61e9e6bbf to your computer and use it in GitHub Desktop.
Save coopermayne/1865d17c56c61e9e6bbf to your computer and use it in GitHub Desktop.
javascript ref
#JAVASCRIPT NOTES
This is for you to reference when doing homework --- this will contain it all!
**Table of Contents**
[TOC]
###data types
```
// variables (user 'var')
var zero = 1;
var name = 'biilliio';
```
###target an element
```
var el = $('h1')
var el = $('.some-class')
var el = $('#some-id')
```
###get information about that element
```
$('h1').text() //gets you the text inside that tag
$('input').val() //gets you the value of an input field
```
###edit the element
```
$('h1').text('New Text For Header') //you can set text this way
$('h1').css('background-color', 'black') //you can set style this way
$('input').val('whatever') //you can even change input field value
```
###create an element
```
var newEl = $('<div>blargstefer</div>')
```
###add element to page
you can add the element to the page in different ways. **append, prepend, before, after**
```
$('ul').append(newEl) //puts newEl at the end of the list targeted by 'ul'
$('ul').prepend(newEl) //same but at beginning
$('ul').before(newEl) // puts newEl b4 'ul' element
$('ul').after(newEl) // right?
```
###function
similar to ruby --- just defined and called a bit differently
```define it
// def
var myFunction = function(){
console.log('this is happening!')
}
// call it
myFunction() //this will run the function!
```
```
// define a func with arguements
var myNextFunction = function(message) {
console.log(message)
}
// call it with arguement
myNextFunction('bargstefer') // this will log 'a function will log 'bargstefer'
// another example
var multiply = function(x,y) {
return x*y
}
multiply(2,4) // this will return... 8
```
###events
first you target the element that you care about; then you tell it what kind of event you care about; the you tell it what to do when that event happens.
```
var iCare = $('h1')
myFunction = function() { console.log('something') }
iCare.on('click', myFunction);
```
now whenever someone clicks on an **h1** element javascript will run **myFunction** which will **log 'something'**
another way (more common)
```
var iCare = $('h1')
iCare.on('click', function(){
console.log('something')
})
```
this code will do the same as the one before it. but it is easier to write.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment