Skip to content

Instantly share code, notes, and snippets.

@sahinsf
Created June 13, 2012 17:34
Show Gist options
  • Save sahinsf/2925407 to your computer and use it in GitHub Desktop.
Save sahinsf/2925407 to your computer and use it in GitHub Desktop.
jQuery 30 - Basics
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<style type="text/css">
ul li{color: red;}
.emphasis{color: green;}
</style>
</head>
<body>
<ul>
<li>Hello</li>
<li>Hello</li>
<li>Hello</li>
</ul>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
//jQuery('ul li'); // search DOM and find ul li(s)
//console.log(lis);
//jQuery('ul li').css('color', 'green');
//jQuery('ul li').addClass('emphasis'); // separate style with content and js
//window.jQuery = window.$ = jQuery;
$('ul li').addClass('emphasis');
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<style type="text/css">
ul li{color: red;}
.emphasis{color: green;}
</style>
</head>
<body>
<ul>
<li>Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
</ul>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
$('li:first-child').addClass('emphasis'); //using the CSS selector only
$('document').ready(function(){
//$('li:first-child').addClass('emphasis'); //using the CSS selector only
});
$(function(){ //short cut for document.ready
$('li:first-child').addClass('emphasis'); //using the CSS selector only
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<style type="text/css">
ul li{color: red;}
.emphasis{color: green;}
ul.emphasis > li {}
</style>
</head>
<body>
<div class="container">
<ul class="emphasis">
<li>Hello 1</li>
<li>Hello 2</li>
<li>
<ul>
<li>Hello 3</li>
</ul>
</li>
</ul>
</div>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
//=============day3 Querying the DOM============
$('ul.emphasis').children('li'); //get the direct children (not nested ones) like CSS: ul.emphasis > li {} NOT ul.emphasis li {}
$('ul.emphasis').find('li'); //get all li (even nested ones) like CSS: ul.emphasis li {}
//!!! 4 li elements found
$('ul.emphasis').find('li:first-child'); //CSS
$('ul.emphasis').find('li:nth-child(1)'); //CSS
$('ul.emphasis').children('li:first'); //jQuery helper
$('ul.emphasis').children('li').first();//jQuery method
$('ul.emphasis').children('li:nth-child(2)'); //second child CSS
$('ul.emphasis').children('li').eq(1); //second child jQuery method
$('ul.emphasis').children('li').eq(3).next(); // jQuery method
$('ul.emphasis').children('li').eq(3).prev(); //jQuery method
$('li').parent().removeClass('emphasis'); //direct parent NOT all parents above
$('li').parent('ul').removeClass('emphasis'); //more specific
$('li').parents('div.container').removeClass('container'); // only 'parents' wouldnt work because div is not a direct parent
$('li').closest('div.container').removeClass('container'); //'closest' method starts searching from current element, and progressing up through the DOM tree
// closest is a filtered version of parents
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<link rel="stylesheet" href="day.css" />
</head>
<body>
<div class="container">
<h1> Banner </h1>
<button data-file="day">Day</button>
<button data-file="night">Night</button>
</div>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
//====================day4 Events 1=========================
(function(){
var link = $('link');
$('button').on('click', function(){
console.log(this);// refferring the regular DOM node with 'this' ==> cannot access jQuery methods
console.log($(this));
var uls = $('ul'); // everytime you are diving into the DOM and return all of the ul wrapped in jQuery ==> SO CACHE ONCE and use multiple times
var $this = $(this);
//var stylesheet = $(this).text().toLowerCase(); //1
//var stylesheet = $(this).attr('data-file'); //2 html5
var stylesheet = $this.data('file'); //3 html5
link.attr('href', stylesheet +'.css');
//!!! when you pass 1 parameter you are returning an attribute value,, passing 2 parameter setting the attribute value
$this //chaining
.siblings('button')
.removeAttr('disabled')
.end() //end() siblings steck and back to refer $this
.attr('disabled', 'disabled'); // set
});
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<style type="text/css">
body{
width: 500px;
margin: auto;
text-align: center;
}
dl{
}
dd{
margin: 0;
padding: 1em 0;
}
dt{
cursor: pointer;
font-weight: bold;
font-size: 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
</style>
</head>
<body>
<dl>
<dt>What are your hours?</dt>
<dd>We are open 24/7</dd>
<dt>What are your hours?</dt>
<dd>We are open 24/7</dd>
<dt>What are your hours?</dt>
<dd>We are open 24/7</dd>
<dt>What are your hours?</dt>
<dd>We are open 24/7</dd>
</dl>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
(function(){
//$('dd').hide(); //jQuery
$('dd').filter(':nth-child(n+4)').addClass('hide'); //css
//$('dt').on('mouseenter', function(){ //use event delegation,, attach event to the parent instead of every dt element
$('dl').on('mouseenter', 'dt', function(){
$(this)
.next().slideDown(200) // open this dt's dd
.siblings('dd').slideUp(200); //if there is an open sibling dd,, slide it Up
});
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<link rel="stylesheet" href="day.css" />
<style type="text/css">
body{
width:500px;
margin: auto;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2>Click Me</h2>
</div>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
(function(){
//BIND DELEGATE LIVE ON
//$('h2').click(function(){ //refers to .on() //used to refer .bind()
//$('h2').bind('click', function(){ //does not apply to dynamically created elements
//$('h2').live('click', function(){ //implements event delegation
//live() event delegation DEFAULT CONTEXT: body //attaches only 1 event handler to the document (top parent)
//$('h2', $('.container')[0]).live('click', function(){ // specifying delegation explicitly
$('.container').delegate('h2', 'click', function(){ // selector specifies the CONTEXT
//in jQuery 1.6.4 delegate it was pointing to the .live() method
//in jQuery 1.7 all event handlers are pointing to the .on() method
console.log("clicked!");
$(this).clone().appendTo('.container'); //clone the element,, throw it into the DOM,, than appendTo the container
//$(this).clone('true').appendTo('body'); // clone also the event handlers that has been attached to the elements,, default is FALSE
});
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<link rel="stylesheet" href="day.css" />
<style type="text/css">
body{
width:500px;
margin: auto;
text-align: center;
}
</style>
</head>
<body>
<article>
<h1>My Awesome Post</h1>
<!-- <h1>My Awesome Post2</h1> -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel lorem turpis, non rhoncus ipsum. Aenean ultrices congue diam, nec sagittis diam volutpat et.
</p>
<p>
<span class="co">Lorem ipsum dolor sit amet</span>, consectetur adipiscing elit. Aenean vel lorem turpis, non rhoncus ipsum. Aenean ultrices congue diam, nec sagittis diam volutpat et.
</p>
</article>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
(function(){
//$('article').append('Hello from the Javascript');
//$('p').prepend('<p>Hello from the Javascript</p>');
//$('h1').after('<p>Hello from the Javascript</p>');
//$('p').first().before('<p>Hello from the Javascript</p>');
//$('<h2>Hello from the Javascript</h2>').appendTo('article'); // mixing javascript with HTML is sloppy !!! ==> templating or splitting up the job
$('<h2></h2>', {
text: 'Hello from Javascript',
class: 'myClass'
//}).prependTo('article');
}).insertBefore('p:nth-child(3)'); //css index starts with 1
// nth-child counts all children of a parent (!!!not 3rd "p" but 3rd child)
//$('h1').appendTo('article'); // !!!MOVEd the element!!!
//$('p').eq(0).after($('h1'));
$('p').eq(0).after(function(){
return $(this).prev(); // grab the previous element of the first "p" //and place it "after" the first "p"
});
//var $(this) = $this;
//var co = $('span.co').each(function(){
var co = $('article').find('span.co').each(function(){ //better performance
var $this = $(this);
$('<blockquote></blockquote>', {
class: 'co',
text: $this.text()
}).prependTo($this.closest('p'));
});
})();
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Slides and Structure</title>
<style>
body {
width: 600px;
margin: auto;
font-family: sans-serif;
}
#contact {
background: #e3e3e3;
padding: 1em 2em;
position: relative;
}
.js #contact { /* if js enabled */
position: absolute;
top: 0;
width: inherit; /*equal to its container */
display: none;
}
#contact h2 { margin-top: 0; }
#contact ul { padding: 0; }
#contact li {
list-style: none;
margin-bottom: 1em;
}
/* Close button on form */
.close {
position: absolute;
right: 10px;
top: 10px;
font-weight: bold;
font-family: sans-serif;
cursor: pointer;
}
/* Form inputs */
input, textarea { width: 100%; line-height: 2em;}
input[type=submit] { width: auto; }
label { display: block; text-align: left; }
</style>
</head>
<body>
<article>
<h1>My Awesome Post</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
<div id="contact">
<h2>Contact Me</h2>
<form action="#">
<ul>
<li>
<label for="name">Name: </label>
<input name="name" id="name">
</li>
<li>
<label for="email">Email Address: </label>
<input name="email" id="email">
</li>
<li>
<label for="comments">What's Up?</label>
<textarea name="comments" id="comments" cols="30" rows="10"></textarea>
</li>
<li>
<input type="submit" value="Submit">
</li>
</ul>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
//siaf: self invoking anonymous function
(function() {
$('html').addClass('js'); // if js enabled
//provide a structure for applications
var contactForm = { //1- create a parent object
container: $('#contact'), //5- defined var for grabbing contact div
config: {
effect: 'slideToggle', // !!! string
speed: 300
},
init: function(config){ //2.a- in OOP "constuctor" method //gets the ball rolling // is 'init' a global var ??????
//console.log(this); //'THIS' refers to contactForm{}
$.extend(this.config, config); //apply a default object ==> we already created that: config{}
//here 'this.config' is target object , 'config' user passed to override default object
$('<button></button>', { //3.a- create a button that will toggle form display
text: 'Contact Me'
}).insertAfter('article:first') //3.b- insert it after first article
.on('click', //3.c- attach event handler function(){$('#contact').show();} // instead of passing an anonymous fn, we will pass a named fn
this.show // 'THIS' refers to contactForm{} object // so this.show is show() method of contactForm{} object
// NOT 'show()' because we dont wanna execute this method right away while JS is parsing the code first time
);
},
show: function(){ // 4- define the method attahced to the click event handler (named function)
// $('#contact').show(); instead create a variable
if(contactForm.container.is(':hidden')){
contactForm.container[contactForm.config.effect](contactForm.config.speed); //was contactForm.container.show();
//this.container.show(); //would work when called from contactForm.show();
//console.log(this); //!!! refers to contactForm{} when called from contactForm.show();
//!!! refers to <button> when called in on.click
contactForm.close.call(contactForm.container); //when we call close() 'this' now refers to container
}
},
close: function(){
//console.log(this); //'THIS' should refer to container{} but refers contactForm now //??? use call() to make it happen
var $this = $(this); // cached this to be able to point container{} inside the .on('click', function(){
if( $this.find('span.close').length ){return};
$('<span></span>', {
text: 'X',
class: 'close'
}).prependTo(this)
.on('click', function(){
//'THIS' = SPAN but we need 'container = #contact' so cache the $(this) above and use here.. !!!
//console.log(this); //still same
//console.log($this); // now refers container{}
$this[contactForm.config.effect](contactForm.config.speed); //was $this.hide();
});
}
};
//contactForm.close();
//contactForm.show();
contactForm.init( //2.b- INIT gets everything started
{ //pass custom object
effect: 'fadeToggle',
speed: 2000
}
);
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<link rel="stylesheet" href="day.css" />
<style type="text/css">
</style>
</head>
<body>
<a href="https://tutsplus.com/lesson/the-this-keyword/"> Click Me </a>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script >
console.log(this); //parent Window Object
/*
(function doSomething(){
console.log(this); //parent Window Object
})();
*////////////////////////////////////////////////////////////////
//COPYING
/*
function doSomething(e){
e.preventDefault();
console.log(this); //'a' element ==> parent object is anchor tag here
};
$('a').on('click', doSomething); // anchor owns doSomething method(function)
// == $('a').on('click', this.doSomething);
*/
/////////////////////////////////////////////////////////////////////
//REFERRING
//you do not copy the function! Instead, you refer to it, and the difference is crucial.
//The onclick property does not contain the actual function, but merely a function call:
//So it says “Go to doSomething() and execute it.” When we arrive at doSomething() the this keyword once again refers to the global window object
/*
function doSomething(){
//e.preventDefault();
console.log(this); //window object ==> parent object is window here
};
$('a').on('click', function(e){ // anchor owns an annonymous fn and it calls(refers) doSomething
e.preventDefault();
doSomething();
});
*/
//////////////////////////////////////////////////////////////////////
//COMBINATION: Passing 'this' as an argument from anchor
/*
function doSomething(arg){
//e.preventDefault();
console.log(arg); //'a' element ==> parent object is anchor tag here
};
$('a').on('click', function(e){
e.preventDefault();
doSomething(this);
});
*/
////////////////////////////////////////////////////////////////
/*
var obj = {
doIt: function(e){
e.preventDefault();
console.log(this); // 'a' element
}
};
$('a').on('click', obj.doIt);
*/
/////////////////////////////////////////////////////////////
//1- pointing obj{} with passing annonymous fn
/*
var obj = {
doIt: function(){
console.log(this); // obj{}
}
};
$('a').on('click', function(e){ // you should not execute '()' callback function
e.preventDefault();
obj.doIt();
});
*/
//////////////////////////////////////////////////////////
/*
//2- pointing 'a' with "call" or "apply" methods
var obj = {
doIt: function(){
console.log(this); 'a' element
}
};
$('a').on('click', function(e){ // you should not execute '()' callback function
e.preventDefault();
obj.doIt.call(this);
});
*////////////////////////////////////////////////////////////////////
//3- pointing obj{} with $.proxy(method, reference to point 'this')
var obj = {
doIt: function(e){
e.preventDefault();
console.log(this); // 'a' element
}
};
$('a').on('click', $.proxy(obj.doIt, obj));
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Effect Speeds / Custom Effect Methods</title>
<style>
p { margin-top: 0;}
</style>
</head>
<body>
<h1>Reveal</h1>
<div class=content>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$('div.content').hide();
console.log(jQuery.fx.speeds);
//overriding _default
$.fx.speeds._default = 450;
$.fx.speeds.tortoise = 5000;
$('h1').on('click', function(){
//$(this).next().slideDown(1000);
$(this).next().slideDown('slow'); //'fast': 200 //'_default': 400
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment