JavaScript-Basics

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .childcontainer{   /*class added through javascript*/
            background-color: cyan;
        }
        .classcontainer{       /*class added through javascript*/
            border: 2px solid goldenrod;
            border-radius:5px;
        }
    </style>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Tutorial</title>
</head>
<body>
    <h1>Welcome to my Javascript</h1>
    <div class="container" id="firstcontainer">
        <button id="click" onclick="clicked()">ClickMe</button>
        <p>This is a paragraph</p>
    </div>
<script>
    //1. ways to print in javascript
    //console.log("Hello World");
    // document.write("This is document write");
    //alert("this is an alert");

    
    //2. Javascript console API 
    
    console.log("hello world",1600+1400,"Another one" );
    console.warn("This is a warning");
    console.error("This is an error");
    //console.clear();


    //3. Javascript variables(containers to store data values)
    // var number1=3;
    // var number2=5;
    // console.log("This is the sum: ",number1+number2);

    // 4. Data types in Javascript
    // Numbers
    // var num1=456;
    // var num2=895;

    // String
    // var str1="This is a string";
    // var str2="This is another string";

    // Objects
    // var marks={
    //     raj:54,
    //     manav:34,
    //     priyansh:99.56
    // };


    // Booleans
    // var a= true;
    // var b= false;
    // console.log(a,b);

    
    // var un=undefined;
    // console.log(un);
    // var n=null;
    // console.log(n);
/*
    At a very high level, there are two types of data types in Javascript
    1. Primitive data types: undefined, null, number, string, boolean, Symbol
    2. Reference data types: Arrays and Objects
*/

// Arrays
    // var arr=[34,5,45,7] ;
    //console.log(arr);


    // Operators in Javascript

// Arithmetic Operators
// var a =100;
// var b=10;
// console.log("The value of a+b is ",a+b);
// console.log("The value of a-b is ",a-b);
// console.log("The value of a/b is ",a/b);
// console.log("The value of a*b is ",a*b);

// Assignment Operators
/*var c=10;
var c=b;
c+=2
c-=2
c*=2
c/=2
console.log(c); */

//Comparison Operator
// var x=200;
// var y=300;
// console.log(x==y);
// console.log(x!=y);
// console.log(x<=y);
// console.log(x>=y);

// Logical Operators
//Logical AND
// console.log(true && false);
// console.log(false && false);
// console.log(true && true);
// console.log(false && true);
// Logical OR
// console.log(true || false);
// console.log(false || false);
// console.log(true || true);
// console.log(false || true);
// Logical not
// console.log(!false);
// console.log(!true);


//Functions in javascript
// function avg(a,b){
//     return (a+b)/2
// }
// var c1=avg(100,10);
// var c2=avg(100,50);
// console.log(avg(c1,c2));


// Conditionals in javascript

// Single if statement
// var age=19;
// if(age<18){
//     console.log("You are not an adult");}

// if-else statement
// var age=19;
// if(age<18){
//     console.log("You are not an adult");}
// else{
//     console.log("You are an adult");
// }

// if-else ladder
// if(age>50){
//     console.log("You are very old");}
// else if(age>40){
//     console.log("You are old");
// }
// else if(age>30){
//     console.log("You are growing");
// }
// else if(age>20){
//     console.log("You are young");
// }
// else if(age>10){
//     console.log("You are very young");
// }
// else{
//     console.log("You are a kid");
// }

// for loop
var arr=[2,36,76,7,21,34]
// console.log(arr)
// for (var i=0;i<arr.length;i++){
//     console.log(arr[i])
// }

//for each
// arr.forEach(function(element){console.log(element);})

// let and const
// let j=0;
// const ac=3;
// ac++   this is an error because acc is a constant;

// while loop
// let j=10;
// while (j<arr.length){
//     console.log(arr[j]);
//     j++;
// }

// do while loop
// do{
//     console.log(arr[j]);
//     j++;
// }
// while (j<arr.length); Difference between while and do while loop is that do while
// will run once ,whether the condition is true or not


// break  and continue
    // for (var i = 0; i < arr.length; i++) {
    //     if (i == 3) {
    //         break
    //     }
    //     console.log(arr[i])
    // }


let myarray=['tata','birla',41,60,8];
//Array Methods
// console.log(myarray.length);
// myarray.pop(); to remove the last item of the array
// myarray.push('ambani'); to add items from the last of the array
// myarray.shift(); It removes item of an array from index no. 0
// myarray.unshift('godrej');It add items of an array from index no. 0
// console.log(myarray.toString()) it convert items of array into string;
// console.log(myarray.sort(function(a,b){
//     return(a-b);
// }));   Without the function the sort is not able to do sorting of numbers.To make
// in descending just use b-a or use reverse function.
// console.log(myarray.reverse());
// splice(startindex,deletecount,value1,value2....) given below
// myarray.splice(0,5,'godrej','pichai','buffets');here it will delete 5 elements from index 0
// and add three elements
// console.log(myarray);

// String Methods in javascript
let mystring="Harry Potter is a Wizard.Harry Potter is an emotion";
// console.log(mystring.length);
// console.log(mystring.toUpperCase());
// console.log(mystring.toLowerCase());
// console.log(mystring.indexOf("otter"));
// console.log(mystring.lastIndexOf("otter"));
// console.log(mystring.slice(2,8)) from index 0 to 7;
// console.log(mystring.repeat(2));
// console.log(mystring.replace("Harry Potter","Professor Dumbledore")); It will replace 
// the first occurence of the word(not all harry potter will change).
// console.log(mystring.split("Harry Potter").join("Professor Dumbledore")); this is
// for replacing all occurence


// Date
var mydate=new Date();
// var date=mydate.getDate();
// var day=mydate.getDay();
// var time=mydate.getTime();  it will give no. of milliseconds since Jan 1,1970 
// var year=mydate.getFullYear();
// var hour=mydate.getHours();
// var min=mydate.getMinutes();
// var sec=mydate.getSeconds();
// var milsec=mydate.getMilliseconds();
// var fulltime=mydate.toLocaleTimeString();
// var fulldate=mydate.toLocaleDateString();

// DOM Manipulation

 var head=document.getElementsByTagName('h1');
//  console.log(head[0]); for data with tag name
//  console.log(head[0].innerHTML);  for only data inside tag
 head[0].style.backgroundColor="hotpink";
 head[0].style.border="2px solid black";
 head[0].style.borderRadius="10px";

//  console.log(document.location);this will give location of htmlpage

var click=document.getElementById("click");
click.style.backgroundColor="teal";
click.style.color="orange";
click.style.display="block";
click.style.margin='auto';

var cont=document.getElementsByClassName("container");
// cont[0].classList.add("fun","sun");     to add class
cont[0].classList.add("childcontainer","classcontainer");  
// cont[0].classList.remove("fun","sun"); to remove class

//To add or remove child element
var newpara=document.createElement("p");
cont[0].appendChild(newpara); 
cont[0].removeChild(newpara);

var createpara=document.createElement("p");
cont[0].appendChild(createpara);
createpara.innerText="This is a new paragraph";
var createpara2=document.createElement("b");
createpara2.innerText="This is a bold sentence";
cont[0].replaceChild(createpara2,createpara);

//Selecting using Query
// sel=document.querySelector('.container');
// console.log(sel);
// selall=document.querySelectorAll('.container');
// console.log(selall);


// Events in javascript
function clicked(){
    console.log("Button is clicked");
}
// window.onload=function(){    this is will work when document loaded
//     console.log("The document was loaded");
// }

/*As you can see below that we can access containers directly through their id
NOTE: Do not use "on" during using addEventListener but use it only with inline event 
   handler(i.e. during using in HMTL)*/
// firstcontainer.addEventListener('click',function(){
//     console.log("container is clicked");
// })

// firstcontainer.addEventListener('mouseover',function(){
//     var conta=document.querySelector(".container");
//     conta.innerText="You had mouseover.Reload to make it normal";
//     console.log("mouse over container");
// })
// firstcontainer.addEventListener('mouseout',function(){
//     conta.style.backgroundColor="green";
//     console.log("mouse out of container");
// })

firstcontainer.addEventListener('mouseup',function(){
    document.querySelector("div p").innerHTML="You had just leave clicking";
    console.log("This will work as you press and leave");
})
firstcontainer.addEventListener('mousedown',function(){
    document.querySelector("div p").innerHTML="You had just clicked";
    console.log("This works when you click on the");
})


//Arrow function
sums=(a,b)=>{console.log(a+b);}
sums(3,5);


// setTimeout and setInterval
ms=()=>{
    document.querySelector("div p").innerHTML="setTimeout Fired";};
ks=()=>{
    document.querySelector("div p").innerHTML="setInterval Fired";};

setTimeout(ms,3000);
setInterval(ks,2000);
// clr=setInterval(ks,2000);
// clr=setTimeout(ms,3000);
// use clearInterval(clr) and clearTimeOut(clr) to cancel setInterval() or setTimeOut()


// Javascript localStorage
// localstorage:it helps us to store data in the computer.
// to enter item: localStorage.setItem('field','value')
// to delete all items: localstorage.clear()
// to view: localstorage
// to view particular value: localstorage.getItem('field')
// localStorage.setItem('name','raj')  output:undefined
// localStorage.getItem('name')        output:"raj"
// localStorage.clear()                output:undefined


/* JSON(It stands for javascript object notation.It is a lightweight data interchange 
 format)  */
// var obj={name:"Harry",class:12,gender:"male"};  
// Do not use single quotes (only use double quote) for the object to be converted into JSON
//To convert object into jsonstring
// var jso=JSON.stringify(obj);
// console.log(jso);
//To convert jsonstring into object 
// var parsed=JSON.parse(jso);
// console.log(parsed);


//Template literals - Backticks
// let  prdp="Shawshank Redemption";
// console.log(`World Best movie is ${prdp}`)
</script>
</body>

</html>

Comments