Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Last active March 17, 2019 09:22
Show Gist options
  • Save bablukpik/13f2fe78d8335a315f9d04db5aa3b233 to your computer and use it in GitHub Desktop.
Save bablukpik/13f2fe78d8335a315f9d04db5aa3b233 to your computer and use it in GitHub Desktop.
// ----------------------- '+!!' operator in an if statement-------------------------------
It is an unary conversion to give a 0/1 number result
+!!true; //this converts true to false, then to true again, and true is 1 when converted
+!!0; //converts 0 (falsy) to true, then false, and then the numeric 0
Technically speaking !! is not its own operator, it's just the NOT (!) operator twice.
//--------------------------What does “!--” do in JavaScript?-----------------------------------------
! inverts a value, and gives you the opposite boolean:
!true == false
!false == true
!1 == false
!0 == true
--[value] subtracts one (1) from a number, and then returns that number to be worked with:
var a = 1, b = 2;
--a == 0
--b == 1
//OR...
! is the JavaScript NOT operator
-- is a pre-decrement operator. So,
x = 1;
if (!x) // false
if (!--x) // becomes 0 and then uses the NOT operator
// which makes the condition to be true
//------------------------Javascript Object--------------------------------------
//V.01
var myCar = new Object(); //making an object
myCar.model = 'Mustang';
myCar.year = 1969;
//console.log(myCar.year);
console.log(myCar);
//V.02
var obj = {}
obj.foo = 42;
console.log(obj.foo);
//V.03 -Arrays are always objects but property is associated with a string value
var obj = {}
obj.foo = 423;
console.log(obj['foo']);
//V.03.01
var bar = 'foo';
console.log(obj[bar]);
//rest parameters, default parameters or destructured parameters
->The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.
//Destructured Variables/Parameters
var a, b, rest;
[a, b] = [10, 20];
//console.log(a); // 10
//console.log(b); // 20
[a, b, ...rest] = [10, 20, 30, 40, 50,60,70];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50], rest pattern/remaining part
({a, b} = {a: 10, b: 20});
console.log(a); // 10
console.log(b); // 20
var x = [1, 2, 3, 4, 6];
var [y, z] = x;
console.log(y); // 1
console.log(z); // 2
console.log(x); // [1, 2, 3, 4, 6]
var foo = ['one', 'two', 'three', 'four'];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
//Default value set by destructuring expression
var a, b, c=20, d=30;
[a=5, b=7] = [c,d];
console.log(a); // 20
console.log(b); // 30
//Swapping/exchange Variables/values
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
//Parsing an array returned from a function
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
//Ignoring some returned values
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
//Pulling values from a regular expression match
var url = 'https://developer.mozilla.org/en-US/Web/JavaScript';
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
var [, protocol, fullhost, fullpath] = parsedURL;
console.log(protocol); // "https"
console.log(fullhost); // "developer.mozilla.org"
//Object destructuring
//v.01
var testObj = {};
testObj.name = "Md. Bablu Mia";
var {name}=testObj;
console.log(name);
console.log(testObj.name);
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
//v.02
var a, b;
({a, b} = {a: 1, b: 2}); //var {a, b} = {a: 1, b: 2}
//v.03 , Default values
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
//v.04, Setting a function parameter's default value
function drawES5Chart(options) {
options = options === undefined ? {} : options;
var size = options.size === undefined ? 'big' : options.size;
var cords = options.cords === undefined ? {x: 0, y: 0} : options.cords;
var radius = options.radius === undefined ? 25 : options.radius;
console.log(size, cords, radius);
// now finally do some chart drawing
}
drawES5Chart({
cords: {x: 18, y: 30},
radius: 30
});
//v.05
function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES2015Chart({
cords: {x: 18, y: 30},
radius: 30
});
//Nested object and array destructuring
var metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung'
}
],
url: '/en-US/docs/Tools/Scratchpad'
};
var {title: englishTitle, translations: [{url, title: localeTitle}]} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
console.log(url); // "/de/docs/Tools/Scratchpad"
console.log(metadata.translations[0].url); // "/de/docs/Tools/Scratchpad"
//Iteration of destructuring
var people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
for (var {name: n, family: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
//Output:
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
//Pulling fields from objects passed as function parameter
function userId({id}) {
return id;
}
function whois({displayName, fullName: {firstName: name}}) {
console.log(displayName + ' is ' + name);
}
var user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
console.log('userId: ' + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
//This pulls the id, displayName and firstName from the user object and prints them.
//Computed object property names and destructuring
let key = 'p';
let {[key]: boo} = {p: 'bar'}; //default value works as variable
console.log(boo); // "bar"
//Rest Variables
-> The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
Syntax:
function(a, b, ...theArgs) {
// ...
}
//v.01
var x = function(...n){ //...n, n number of arguments, where ... is spread operator
console.log(n);
};
x(1,2,3,4);
//output: [1, 2, 3, 4]
//v.02
var x = function(){
console.log(arguments); //arguments is an obj not array
var arr1 = Array.prototype.slice.call(arguments);
var arr2 = [].slice.call(arguments);
console.log(arr1); //Array like spread operator
};
x(1,2,3,4);
//output: [1, 2, 3, 4]
//v.03
var y = function(a,b,c, ...n){
console.log(n);
};
y(1,2,3,4);
//output: [4]
//v.04
var whatever = ['die', 'keyamot','jannat', 'jahannam'];
var life = ['kalema', 'namaz', 'ibadat', 'kaj', ...whatever];
console.log(life);
//v.05
var whatever1 = ['die', 'keyamot','jannat', 'jahannam'];
var life1 = ['kalema', 'namaz', 'ibadat', 'kaj'];
life1.push(...whatever1); //two array combined
console.log(life1);
// Function constructor
-> The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.
Syntax: new Function ([arg1[, arg2[, ...argN]],] functionBody)
//v.01, Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function('a', 'b', 'return a + b');
// Call the function
adder(2, 6);
// > 8
//v.02, Difference between Function constructor and function declaration
var x = 10;
function createFunction1() {
var x = 20;
return new Function('return x;'); // this |x| refers global |x|
}
function createFunction2() {
var x = 20;
function f() {
return x; // this |x| refers local |x| above
}
return f;
}
var f1 = createFunction1();
console.log(f1()); // 10
var f2 = createFunction2();
console.log(f2()); // 20
//v.03
function make_person(firstname, lastname, age) {
person = {};
person.firstname = firstname;
person.lastname = lastname;
person.age = age;
return person;
}
var bb = make_person("Joe", "Smith", 23);
console.log(bb);
// {firstname: "Joe", lastname: "Smith", age: 23}
//v.04
//Inherit a prototype of function constructor
//A function can reference 'this' and if it is called with the 'new' operator then it will return an object.
function make_person_object(firstname, lastname, age) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
// Note, we did not include a return statement
}
var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); // undefined
console.log(window.firstname) // "Joe" (oops)
var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}
//v.05, Assuming all that came before
function make_person_object(firstname, lastname, age) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
// Note, we did not include a return statement
}
var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); // undefined
console.log(window.firstname) // "Joe" (oops)
var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}
make_person_object.prototype.full_name = "N/A";
make_person_object.prototype.greet = function(){
console.log("Hello! I'm", this.full_name, "Call me", this.firstname);
};
John.full_name // "N/A"
John.full_name = "John Smith";
make_person_object.full_name // Still "N/A"
John.greet(); // "Hello! I'm John Smith Call me John"
//end v.05
//Callback function
//v.01
let x =function(){
console.log("I am called from inside a function");
}
let y =function(callback){
console.log("Do something");
callback();
}
x(); //I am called from inside a function
y(x);
//v.02
let calc = function(num1, num2, calcType){
if(calcType==="add"){
return num1+num2;
}else if(calcType==="multiply"){
return num1*num2;
}
}
console.log(calc(2,3,'multiply'));
//v.03
let add = function(a, b){
return a+b;
}
let multiply = function(a, b){
return a*b;
}
let doWhatever = function(a, b){
console.log(`Here are your two numbers back ${a}, ${b}`);
}
let calc = function(num1, num2, callback){
return callback(num1, num2);
}
console.log(calc(2, 3, doWhatever));
//v.04
let calc = function(num1, num2, callback){ //callback = function(a,b){return a-b;}
if(typeof callback === "function") //typeof returns type of a variable
return callback(num1, num2);
}
console.log(calc(2, 3, function(a,b){return a-b;}));
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
->Array and Object in Javascript
var obj = {}
obj.foo = 42;
var bar = 'foo';
console.log(obj[bar]);
i.e
var objectName[key]{
'someDataName':'thatData',
'someOtherDataName':'thisData'
}
If you want to get value of value so you can use loop
for(key in objectName){
objectName[key].someDataName;
objectName[key].someOtherDataName;
}
//Array and how to add elements
->You don't need jQuery for that. Use regular javascript
var arr = new Array();
// or var arr = [];
arr.push('value1');
arr.push('value2');
//two array combine
var a = ['value1', 'value2', 'value3'];
var b = ['value4', 'value5', 'value6'];
a.push(...b);
console.log(a);
->Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:
var obj = new Object();
Array.prototype.push.call(obj, 'value');
//or
var a = ['value1', 'value2', 'value3'];
->Some Examples of Array
arr = new Array(); // empty array
arr = []; // empty array
arr = new Array(3);
alert(arr.length); // 3
alert(arr[0]); // undefined
arr = [3];
alert(arr.length); // 1
alert(arr[0]); // 3
Pushing to the array:
arr = [3]; // arr == [3]
arr[1] = 4; // arr == [3, 4]
arr[2] = 5; // arr == [3, 4, 5]
arr[4] = 7; // arr == [3, 4, 5, undefined, 7]
arr = [3];
arr.push(4); // arr == [3, 4]
arr.push(5); // arr == [3, 4, 5]
arr.push(6, 7, 8); // arr == [3, 4, 5, 6, 7, 8]
//01//Everything in Javascript is an object besides(except) primitive types.
Javascript has five primitive data types:
1. Number
2. String
3. Boolean
4. Undefined
5. Null
Undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.
Null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
i.e
undefined == null
null == undefined
//02//Array in JavaScript
->The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
->PHP Arrays:
array('Item 1', 'Item 2', 'Items 3') // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2') // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')
->JavaScript Arrays:
Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:
['Item 1', 'Item 2', 'Item 3'] // array (numerically indexed)
->Syntax:
var points = [];
var array-name = [item1, item2, ...];
->An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:
{ first : 'Item 1', second : 'Item 2' } // object (a.k.a. "associative array")
They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.
* Technically everything is an Object in Javascript, please put that aside for this argument. ;)
->The JavaScript operator typeof returns "object".
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits; // returns object
->We can check a variable is array or not:
Array.isArray(fruits); // returns true
-> An array can hold object value, function value and variable value;
->The easiest way to add a new element to an array is using the push method:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
->New element can also be added to an array using the length property:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
->For reverse an array elements:
Syntax: array.reverse();
->The join() method joins all elements of an array into a string.
var a = ['Wind', 'Rain', 'Fire'];
a.join(); // 'Wind,Rain,Fire' //Default is ','
a.join('-'); // 'Wind-Rain-Fire'
a.join(', '); // 'Wind, Rain, Fire'
a.join(' + '); // 'Wind + Rain + Fire'
a.join(''); // 'WindRainFire'
Syntax:
arr.join()
arr.join(separator)
->The split() method splits a String into an array of strings by separating something like "", " ", "-".
Syntax:
str.split([separator[, limit]])
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3); //limit is optional like 3
console.log(splits);
This script displays the following:
["Hello", "World.", "How"]
//03// onclick to a link
<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>
OR
<button onclick="window.location.href='b.php'">Click me</button>
OR
<button id="myButton" class="float-left submit-button" >Home</button>
<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "www.yoursite.com";
};
</script>
//04//Automatic page redirect after a specific time
<title>JavaScript Automatic Page Redirect</title>
<script type="text/javascript">
function pageRedirect() {
window.location.replace("http://www.tutorialrepublic.com/");
}
setTimeout("pageRedirect()", 10000); //After 10 seconds it will be redirected
</script>
//05// hide/show using conditional statement
$(document).ready(function(){
$('#purpose').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business").show();
}
else
{
$("#business").hide();
}
});
});
OR
HTML:
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<form id="business">
<label for="business">Business Name</label>
<input type='text' class='text' name='business' value size='20' />
</form>
CSS:
#business {
display:none;
}
JS:
$('#purpose').on('change', function () {
if(this.value === "1"){
$("#business").show();
} else {
$("#business").hide();
}
});
or Js:
$(".foo, .bar").on("click change", function(e){
var myClass = $(this).is(".foo") ? "foo" : "bar";
if(e.type === "change"){
//DO STUFF UNIQUE TO CHANGE
}
else if(e.type === "click") {
//DO STUFF UNIQUE TO CLICK
}
//DO STUFF THAT IS THE SAME
});
//06// Append/Prepend/After/Before:
append() - Inserts content at the end of the selected elements but inside
prepend() - Inserts content at the beginning of the selected elements but inside
after() - Inserts content after the selected elements but outside
before() - Inserts content before the selected elements but outside
//i.e.1
$("button").click(function(){
$("p").append("<b>Appended text</b>");
});
//i.e.2
$("p").prepend("Some prepended text.");
//i.e.3
<script>
function appendText() {
var txt1 = "<p>Text.</p>"; // Create text with HTML
var txt2 = $("<p></p>").text("Text."); // Create text with jQuery
var txt3 = document.createElement("p");
txt3.innerHTML = "Text."; // Create text with DOM
$("body").append(txt1, txt2, txt3); // Append new elements
}
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button onclick="appendText()">Append text</button>
</body>
//i.e.4
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("img").before("<b>Before</b>");
});
$("#btn2").click(function(){
$("img").after("<i>After</i>");
});
});
</script>
//i.e.5
<script>
function afterText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2, txt3); // Insert new elements after img
}
</script>
//07//Parameter as selector
function hideView(viewTag){
$("#"+viewTag).remove();
}
///Java Script display functions
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().
//08//Javascript empty() function:
->For checking if a string is empty, null or undefined I use:
function isEmpty(str) {
return (!str || 0 === str.length);
}
->For checking if a string is blank, null or undefined I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
->For checking null, empty, whitespace
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
->For checking String length
if (!str.length) {
//do some thing
}
//or
if (str.length == 0) {
}
//or
if(str == "" || str == null)
{
//enter code here
}
-> For checking not blank
I prefer to use not blank test instead of blank
function isNotBlank(str) {
return (str && /^\s*$/.test(str));
}
//09// Function initialization:
->A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object
In java script when you create any object thru constructor call like below
step 1 : create a function say Person.
var name;
function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}
step 2 : create an instance for this function.
var obj=new Person('venkat')
//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}
if you don't want to instantiate this function and call at same time.we can also do like below..
var Person = {
init: function(name){
this.name=name;
},
print: function(){
console.log(this.name);
}
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();
in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.
//10// Javascript anonymous functions
->The function below is actually an anonymous function (a function without a name).
->A function expression has been stored in a variable, the variable can be used as a function
Here’s a typical example of a named function:
function flyToTheMoon()
{
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Here’s the same example created as an anonymous function:
var flyToTheMoon = function()
{
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
//or
var x = function (a, b) {return a * b};
var z = x(4, 3);
//11//Convert string to array
var string = "This is our Bangladesh";
var array = string.split(' ');
alert(array[3]);
</script>
//OR
var string = "This/is/our/Bangladesh";
var array = string.split("/");
alert(array[3]);
</script>
//12// Javascript Function call comptete reference
<!DOCTYPE html>
<html>
<head>
<script>
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
alert("The " + animal.innerHTML + " is a " + animalType + ".");
}
</script>
</head>
<body>
<h1>Species</h1>
<p>Click on a species to see what type it is:</p>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="bird">Owl</li>
<li onclick="showDetails(this)" id="salmon" data-animal-type="fish">Salmon</li>
<li onclick="showDetails(this)" id="tarantula" data-animal-type="spider">Tarantula</li>
</ul>
</body>
</html>
//13// hide view using function
function hideView(viewTag){
$("#"+viewTag).remove();
}
//Javascript Events
div.addEventListener("blur", listener);
div.addEventListener("keyup", listener);
div.addEventListener("paste", listener);
div.addEventListener("copy", listener);
div.addEventListener("cut", listener);
div.addEventListener("delete", listener);
div.addEventListener("mouseup", listener);
//
var table = $("table");
var button;
table.find('td').click(function() {
td = $(this);
button = td.find('button').first();
});
[td, td]
button
[button.item-buyer]0: button.item-buyercontext: tdlength: 1prevObject: n.fn.init[3]__proto__: Object[0]
button.addClass("select_manufacture");
[button.item-buyer.select_manufacture]
The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:
.closest()
Begins with the current element
Travels up the DOM tree until it finds a match for the supplied selector
The returned jQuery object contains zero or one element
.parents()
Begins with the parent element
Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
The returned jQuery object contains zero, one, or multiple elements
.parent()
Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.
Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN
Please note that if you are specifically checking for numbers it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1))
Or
if( value ) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
$( "li" ).get( 0 );
or
console.log( $( "li" )[ 0 ] );
Retrieve the DOM elements
and $() for selector nothing retrieves until we use property
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>get demo</title>
<style>
span {
color: red;
}
div {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<span>&nbsp;</span>
<p>In this paragraph is an <span>important</span> section</p>
<div><input type="text"></div>
<script>
$( "*", document.body ).click(function( event ) {
event.stopPropagation();
var domElement = $(this)[0];
$( "span:first" ).text( "Clicked on - " + domElement);
});
</script>
</body>
</html>
-> Difference between $(this) and $(this)[0]
-> this is the DOM object, whereas $(this) is the jQuery wrapper around same. When using this, you can call DOM methods on it, but not jQuery methods. When using $(this), you can call jQuery methods on it, but not DOM methods.
Optional:
-> $(this) returns/reffers node type 1 (object Object) of the element which means it will return only tagName of the element like a, p, div etc. and $(this)[0] returns/reffers (object Element Object) node type multiple (nodeList) like <a href="#">Link</a> and also returns echild nodes.
-> http://stackoverflow.com/questions/9979172/difference-between-node-object-and-element-object
-> If the element is multiple then we can use $(this)[0], $(this)[1], $(this)[3] ...
-> For example:
-> $('ul')[0] it will return as follows:
<ul id="menu_ul">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Ipad Apps</a></li>
<li><a href="#">Test Apps</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
-> $('ul') it will return as follows:
[ul#menu_ul, prevObject: init(1), context: document, selector: "ul"]
-> $(this)[0].addClass('active'); //It is not possible
->
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
</ul>
With an index specified, .get( index ) retrieves a single element:
console.log( $( "li" ).get( 0 ) );
Since the index is zero-based, the first list item is returned:
<li id="foo">
Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:
console.log( $( "li" )[ 0 ] );
//
vent = works
, action
$("#formId")[0].reset() //All elements under form will reset
// or
$("#formId").get(0).reset()
$('.border_separator').length;
$('<td>').insertAfter('.border_separator');
$('<td style="padding: 1px;">').insertAfter('.border_separator');
<?php include(dirname(__FILE__).'/../dialogs/after_seller_file_choice.php'); ?>
var table = $('<table>');
undefined
var tr = $('<tr>').appendTo(table);
undefined
var td = $('<td>').appendTo(tr);
-> Difference between between '$(this)' and 'this'
Of course there is difference between them. They are not equal.
-> '$(this)' when you're using jQuery.
-> 'this' when you're using Javascript
-> '$(this)' returns node type 1 (Object).
-> 'this' returns node type multiple (element Object)
$(this)[0] === this
Ans: true
$("#myDiv")[0] === document.getElementById("myDiv");
Ans: true
$(this) === this
Ans: false
//
<script type="text/javascript">
/*
var replaceWith = $('<input name="temp" type="text" />'),
connectWith = $('input[name="hiddenField"]');
$('td').inlineEdit(replaceWith, connectWith);
*/
var table = $("table");
function clickEvent(){
var td = $(this);
if($(this).find("input").val()){
//tdValue = $("td input").val();
}else{
//tdValue = td.attr("data-value");
tdValue = td.text();
td.html('<input class="test" type="text" value="'+tdValue+'"/>');
$(this).find("input").focus();
table.find("td").off('click', clickEvent);
}
}
table.find("td").on('click', clickEvent);
table.find("td").focusout(function(){
var td = $(this);
if($(this).find("input").val()){
tdValue = $(this).find("input").val();
//td.attr("data-value", tdValue);
td.html(tdValue);
setTimeout(function() {
table.find("td").on('click', clickEvent);
}, 1000);
}
});
</script>
//
Bablu Ahmed [10:29 AM]
<script type="text/javascript">
var table = $("table");
table.find("td").click(function(){
var td = $(this);
if($(this).find("input").val()){
//tdValue = $("td input").val();
}else{
tdValue = td.attr("data-value");
td.html('<input class="test" type="text" value="'+tdValue+'"/>');
$(this).find("input").focus();
}
});
table.find("td").focusout(function(){
var td = $(this);
if($(this).find("input").val()){
tdValue = $(this).find("input").val();
td.attr("data-value", tdValue);
td.html(tdValue);
}
});
</script>
//
var arr = [];
var object = {};
arr.push(10);
1
arr
[10]
arr.push(15);
2
arr
[10, 15]
arr[0]
10
arr[1]
15
object["hello"] = "hello";
"hello"
object["hi"] = "Welcome"
"Welcome"
object
Object {hello: "hello", hi: "Welcome"}
object["hi"]
"Welcome"
//Regular Expression using exec() methods.
->v.01, g is for global search. Meaning it'll match all occurrences. You'll usually also see i which means ignore case. The "g" flag indicates that the regular expression should be tested against all possible matches in a string.
var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}
output:
Found abb. Next match starts at 3
Found ab. Next match starts at 9
->v.02
var matches = /(hello \S+)/.exec('This is a hello world!');
console.log(matches[1]);
->v.03
var url = 'https://developer.mozilla.org/en-US/Web/JavaScript';
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
var [, protocol, fullhost, fullpath] = parsedURL;
console.log(protocol); // "https"
//File upload/Image preview
->This example simply reads the contents of a file and outputs it in plain text to the console. The onload handler is called when the file is successfully read whereas the onerror handler is called if the file wasn’t read for some reason. The FileReader instance is available inside of the event handler via event.target and it’s recommended to use that instead of referencing the reader variable directly. The result property contains the file contents on success and error contains error information about the failed operation.
//JS
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
//HTML
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
// event.target
-> The target event property returns the element that triggered with the event.
-> event.target property returns Element Object or DOM Object like object HTMLParagraphElemen
i.e, event.target.tagName, event.target.title, event.target.class, event.target.files etc.
N.B, 'this' keyword is also an element object like <p title="Hi testing">If you click on me, I will disappear.</p> and return multi type node
//Checked falsy values are:
""==false?
Ans: true
null == false?
Ans: false
undefined == false?
Ans: false
0 == false?
Ans: true
NaN == false?
Ans: false
We can see that null == false,undefined == false, and NaN == false are not true
That means they are not equal.
A negative falsy value is always true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
// ---------------------Object.assign (Copy One object's to another)--------------------
var obj = { a: 1 };
var obj2 = {};
var copy = Object.assign(obj2, obj);
console.log(copy); // { a: 1 }
// Without Object.assign directly assignment
var obj = { a: 1 };
var obj2 = obj;
console.log(obj2); // { a: 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment