Search This Blog

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Sunday, September 8, 2019

Learn Promise async await in Javascript

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
window.addEventListener("load", function(){

});



function execute(a, b, c)
{
  result = a + b;
  console.log(result);
  //c(result);
}
execute(5, 6, function(data)
{
  console.log(data);
});

var promise = new Promise(function(resolve, reject)
{
  //setTimeout(function()
 // {
//     resolve("Success");
 // }, 2000);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     
       resolve(xhttp.response);
    }
};
xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
xhttp.send();
 
 
});

promise.then(function(data)
{
 console.log(JSON.parse(data));
}).catch(function(err)
{
 console.log(err);
});


//async function foo()
//{
 // return Promise.resolve(1);
// }
//foo().then(alert);


async function foo()
{
     let promise = new Promise(function (resolve, reject)
{
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         resolve(xhttp.response);
         }
};
        xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
        xhttp.send();


 });
  let result = await promise;
  alert(result);
 }
 foo();


 async function foos()
 {
   try {
        let response = await fetch("https://5d74dc3dd5d3ea001425b027.mockapi.io/userss");
let result = await response.json();

  } catch(e) {
    // catches errors both in fetch and response.json
    alert(e);
  }


   

 }
 foos();
</script>

</body>
</html>

Thursday, May 16, 2019

Redirect parent window from an iframe action uisng Javascript

Welcome to  designer dairy blog, here we are going to  discuss how to Redirect parent window from an iframe action

Step1:

Example.html is the main page and  we are loading "example1.html" via an iframe tag.

Example.Html Mark-up

<html>
<head>
<body>
<iframe src="Example1.html"> </iframe>
</body>
</html>

Step2:

Example1.html  we have a button "Click Me", once the button is clicked, we have to redirect to url "www.google.com".

So we have to use window.top.location.href  to redirect parent window from an iframe action.

Html Mark-up - Example2.html

<script>
function changeurl()
{
window.top.location.href = "http://www.google.com";
}
</script>

<a href ="#"  id="accept" onclick="changeurl()"> Click Me </a>

Note: 

If your not using iframe tag, then u can use window.location.href to redirect parent window.

Step3:

Thanks for reading the article.Stay Tuned on www.webdesignersdairy.com  for more updates on Javascript.



Monday, November 13, 2017

how to reset scroll position in a div using javascript

Step1:

Welcome to designers dairy blog, Here We are going to discuss, how to reset scroll position in a div using javascript

Step2:

Let us consider you have table-grid with pagination inside the scroll.When we are scrolling down and clicking the next or number 2 button.
it has to show the second set of data on top position but inthis case we have to move the scroller to top to view the contents.

Step3:

To tackling this problem, Calling this function after transition between view ,will reset my scroll position.

Step4:

function resetScrollPos(selector) {
  var divs = document.querySelectorAll(selector);
  for (var p = 0; p < divs.length; p++) {
    if (Boolean(divs[p].style.transform)) { //for IE(10) and firefox
      divs[p].style.transform = 'translate3d(0px, 0px, 0px)';
    } else { //for chrome and safari
      divs[p].style['-webkit-transform'] = 'translate3d(0px, 0px, 0px)';
    }
  }
}
resetScrollPos('.mblScrollableViewContainer');

Step5:

Enjoy Folks

Saturday, March 18, 2017

Removing the passenger Using an array and functions to keep track of train passengers

 Step1:
Welcome to designer blog, Here we  are going to discuss , how to delete the names in the passenger
list array


Step2:

We  have to initialize two parameters with your own choice...

here we have declared  name and list  here...

list is called passengerList and name which we are going to delete manual while calling the function

var passengerList = ["Babu", "kumar", "Raja"];

Step3:

Function name called deletepessanger 

function deletepassanger(name, list) {
    if (list.length == 0) {
        console.log('list is empty');
    }
    else {
        for (var i = 0; i < list.length; i++) {
           
            if (list[i] == name)
            {
                list[i] = undefined;
                return list;
            }
            else if (i == list.length-1)
            {
                console.log("Passenger not found!");
            }

        }
    }
    return list;
}

Step4 :

var passengerList = ["faizal", "khan", "Basha"];

deletepassanger("faizal", passengerList);

Console output:

passengerList

[undefined, "Khan","Basha"];





Using an array and functions to keep track of train passengers

Step1:



Welcome to designer blog, Here we  are going to discuss , how to add the names in the passenger
list array

var passengerList = ["Babu", "kumar", "Raja"];

Step2:

We  have to initialize two parameters with your own choice...

here we have declared  name and list  here...

list is called passengerList and name which we are going to add manual while calling the function

Step3:

Function name called addpessanger



function addpassanger(name, list) {
    if (list.length == 0) {
        list.push(name);
    }
    else {

        for (var i = 0; i < list.length; i++) {

            if (list[i] == undefined) {
                list[i] = name;
                return list;
            }
            else if (i == list.length-1)
            {
                 list.push(name);
                return list;

                }
            }

        }

}


Step4:

addpassanger("faizal", passengerList);
addpassanger("Ashley Smith", passengerList);


output:
console panel :


passengerList;
["Ashley Smith", "Kumar", "Arun"];



Thursday, September 15, 2016

Toggle method using javascritpt

 Step1:
 

Welcome to designers blog,  Here i have posted how to use toggle effect using Javascript


Step2:

Here we go for the script...

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var active = document.querySelector(".accordion.active");
    if (active && active != this) {
      active.classList.remove("active");
      active.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  }
}

 Step3:

Here we go for the styles...

 <style type="text/css">
 .accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding:10px!important;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

.accordion.active, .accordion:hover {
    background-color: #ddd;
}

.accordion:after {
    content: '\02795';
    font-size: 13px;
    color: #2a6496;
    float: right;
    margin-left: 5px;
}

.accordion.active:after {
    content: "\2796";
}

div.panel {
 
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: 0.6s ease-in-out;
    opacity: 0;
    margin-bottom:0px!important;
}
.hide
{
    display:none;
}
div.panel.show {
    opacity: 1;
    max-height: 100%; 
}
div.panel.hide {
    display:none; 
}
</style>

 Step5:

Entire mark up 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<h2 class="accordion active">Elementary Campus</h2>
<div class="row panel show">
   <div class="col-md-9">
      <p>Education has been rapidly transforming over the last five years. Our students are no longer asked to memorize and rote -learn rather they are asked to compare, contrast and demonstrate their understanding. These skills are higher order critical thinking skills that will transform each child into a citizen ready for the future.</p>
      <p>At ADNOC Schools we pride ourselves on high expectations and are happy to announce that ADNOC Schools received full international accreditation from the Middle States Association which solidifies our reputation as a premier school in the Middle East.</p>
      <p>Your child is a child of the 2020 vision of the United Arab Emirates and of a future that we do not yet know. It will be their ability to imagine connections, transfer knowledge into new unknown scenarios with courage that will see them thorough. I want your child to know that NASA students are not chosen for their academics alone rather for their determination to keep trying after every failure and keep focused on their goals.</p>
      <p>I look forward to continuing a partnership with you next year and thank everyone for their support and commitment to the highest quality of education.?</p>
   </div>?
   <div class="col-md-3 mg-responsive ms-rteImage-4" style="Padding-top:15px;padding-bottom: 0px;">
      <img align="right" src="/Style%20Library/GLENELG/Images/Paula%20MussonElementaryPrinciple.jpg" alt="" style="width: 180px;"/>
      <b>
         <p>Paula Musson</p></b>? </div>
</div>
<h2 class="accordion">Male Campus</h2>
<div class="row panel">
   <div class="col-md-9">
      <p>Dear ADNOC Male Campus Community of parents, learners and friends, </p>
      <p>It is a great pleasure to welcome you to our school for the 2015-2016 academic year. We are very proud of the efforts of the teachers and support staff as we move our campus community forward and ever upward. We are a building filled with energy, and this is reflected in the work that goes on in classroom lessons every day, done in a spirit of teamwork with cooperation and respect. The world economy no longer rewards people just for what they know. Google knows everything. The world economy rewards people for what they can do with what they know. The ADNOC schools are committed to a rigorous application of a standards based curriculum that is aligned with the programs in the United States, leading up to the challenges of Advanced Placement (AP) classes in the last several high school years, thereby providing our students with the opportunity to apply to and attend some of the finest universities and post-high school programs in the world. One particular emphasis for us in the curriculum is a move to adding elements of STEAM (Science Technology Engineering Arts Math) to all areas of our curriculum, and this is a focused challenge for our faculty  with the support of the curriculum office of ADNOC schools.</p>
      <p>A strong relationship between the school and parents is needed to support students and we were pleased to see a more than 100% increase in the amount of parents taking the opportunity to attend the “Back to School” program in mid September. I was particularly impressed with the dozen student volunteers who served as guides to parents that afternoon, and these students are a fine example of the great work done at this school to grow our boys into young gentlemen. We look forward to many more such events, while also working with parents 1-on-1 to ensure that we do our best to keep parents informed of student progress at school. Our partnership with parents is goal we have as a school to develop in our students a school culture where the National Identity as well as Arabic and Islamic values are honored on a daily basis, while also seeking to connect these to the world where we live as we roll forward farther into the 21st century. We hold daily assemblies to start each day with the National Anthem, and then a student reader recites from the Quaran as a reminder of the national and religious respect held in such high esteem by ADNOC schools.</p>
      <p>I take great pleasure in seeing the “extra” things done by staff for your sons. For example, the staff who on their own helped 50+ student to organize the Iftar celebration on September 21st was a wonderful example of students from all over the world coming together to share a special evening together with their teachers. Another special event was the STEAM special event on September 22nd where all the boys in school that day and all the teachers made teams to have a contest to build the highest tower possible with a limited amount of tape and a stack of newspapers. The creativity, team building and focus that the boys and their teachers exhibited that day was exiting to see, and we plan to do many more such activities to combine fun with positive educational experiences.</p>
      <p>There are various means with which you can communicate with us on the Male Campus. Feel free to call the office to speak with the Secondary School principal’s assistant Ms. Dana Tamini to make appointments to speak to teachers, supervisors, the counselor Mr. Brandon, and Mr. Jeff Sykes, the Vice Principal. You may also email the school staff and even leave a note in the “Parent Suggestion Box” in the male campus front lobby whenever you wish to communicate in writing.<br/></p>
      <p>Together we can help your sons achieve high levels of academic excellence and at the same time help them grow as young leaders of tomorrow, the leaders that are needed for a better, brighter future in the UAE and all over the world. We are committed to doing our best to provide your sons with the best possible social and educational experience we can at ADNOC schools, and I personally look forward to facilitating for staff and teachers so that they can inspire your sons to achieve their very best each and everyday.</p>
      <p>Our emphasis must be on the application and the creative use of knowledge, and at ADNOC Male Campus that is our goal with our students, your sons. </p>
      <p>Thank you for your support  and I look forward to meeting every one of you as the school year progresses. </p>
   </div>
   <div class="col-md-3 mg-responsive ms-rteImage-4" style="Padding-top:15px;padding-bottom: 0px;">
      <img align="right"  src="/Style%20Library/GLENELG/Images/Jim-Pastore.png" alt="" style="width: 180px;"/>?<b style="line-height: 1.42857; background-color: initial;">
         <p style="display: inline !important;">James (Jim) Pastore</p></b><br/><b>?</b>? ?</div>
</div>
<h2 class="accordion">Female Campus? </h2>
<div class="row panel">
   <div class="col-md-9">
      <p>The act of shaping today’s youth and framing them to become tomorrow’s leaders; the creation of citizens who can carry on a monumental legacy that this country has created is what defines ADNOC Schools. Amidst a changing world, the school has modified and also morphed to incorporate the changing needs of our students. By placing emphasis on building their confidence, their sense of identity, and giving them the tools to succeed in college and career worlds, ADNOC Schools has planted seeds that will continue to be cultivated and grown. We have watched the successes of our efforts, of the effort of the parents and the endless of effort of our students foment and come to fruition in front of our eyes through the outputs our students have put forth throughout the year. </p>
      <p>As the years go by, what we have been creating is an innovative, independent, informed, skilled generation ready to face the challenges and the needs of the 21 century.</p>
      <p>Congratulations to each and every member of ADNOC Schools, SAN Campus, the “A” rating as per ADEC’s latest inspection, February 2016. The credit for this rating goes to the whole school community, faculty and staff, students and parents, and supportive board.</p>
      <p>We are ADNOC Schools; an educational entity that prides itself on placing its students in the forefront and watching them succeed and develop as a result. As the years go by, what we have to hold are the wonderful memories created with our ADNOC Schools family preserved in our hearts and minds, shining through and reaching out to the community.</p>
      <p>?We are ADNOC Schools, we make a difference.</p>
   </div>?
   <div class="col-md-3 mg-responsive ms-rteImage-4" style="Padding-top:15px;padding-bottom: 0px;">
      <img align="right"  src="/Style%20Library/GLENELG/Images/Abufemale.jpg" alt="" style="width: 180px; "/>
      <b>
         <p>Lamia Najjar</p></b>? </div>
</div>
<br/>


<style type="text/css">
 .accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding:10px!important;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

.accordion.active, .accordion:hover {
    background-color: #ddd;
}

.accordion:after {
    content: '\02795';
    font-size: 13px;
    color: #2a6496;
    float: right;
    margin-left: 5px;
}

.accordion.active:after {
    content: "\2796";
}

div.panel {
 
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: 0.6s ease-in-out;
    opacity: 0;
    margin-bottom:0px!important;
}
.hide
{
    display:none;
}
div.panel.show {
    opacity: 1;
    max-height: 100%; 
}
div.panel.hide {
    display:none; 
}
</style>
<script type="text/javascript">
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var active = document.querySelector(".accordion.active");
    if (active && active != this) {
      active.classList.remove("active");
      active.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  }
}
</script>
</body>
</html>

Step6:

Enjoy Folks
 

Wednesday, August 24, 2016

Adding content dynamically using javascript.

Welcome to designers dairy blog, here we are going to discuss about, how to add the content dynamically using java script.

While clicking the submit button content to display and label to be change overlay. when clicking the overlay button transparent background should appear.


Step1:

We are creating div and storing in variable div  var div = document.createElement('div');

Adding the class to the created div by giving  div.className = 'row';  and adding the content using

div.innerHTML = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

now we are appending  div by using document.body.appendChild(div);

Step2: 


Scenario is content should be shown below the button  so we have to  use insertBefore syntax.

document.body.insertBefore(div, document.body.firstChild);

Step3: 

Important thing is dom should be loaded after that script should be executing, for that we are using

<script type="text/javascript">

document.addEventListener("DOMContentLoaded", function(event) {

        var x = document.getElementById("myButton1");
x.addEventListener("click", addContent);


});


Step4:

Creating the submit button dynamically   

function addButton() {
   var divbutton = document.createElement('div');

   divbutton.innerHTML = '<button type="submit" id="myButton1" value="">Submit</button>';
    
   document.body.appendChild(divbutton); 
   
}

Step5:
 
while calling the add function we have to check the if innerHTML is Submit { executed code} or

apply color { document.getElementsByClassName("row")[0].style.cssText += 'background-color: #000; opacity:0.5'};


Step6:

Entire  Script

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
.row
{
    background-color:red;
    color:#fff;
    line-height:24px;
    font-family:Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
  //do work
     addButton();
     var x = document.getElementById("myButton1");
x.addEventListener("click", addContent);
//x.addEventListener("click", overlay);

});
function addContent() {  
     var dip = document.getElementById("myButton1").innerHTML;
      if( dip==="Submit")
 {
   var div = document.createElement('div');
   div.className = 'row';
   div.innerHTML = "Lorem Ipsum is simply dummy text of the printing and typesetting   industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
  document.body.appendChild(div);
 document.body.insertBefore(div, document.body.firstChild);
 document.getElementById("myButton1").innerHTML="Add overlay";
 }
 else
 {
  document.getElementsByClassName("row")[0].style.cssText += 'background-color: #000; opacity:0.5';
      }
}
function addButton() {
   var divbutton = document.createElement('div');
   divbutton.innerHTML = '<button type="submit" id="myButton1" value="">Submit</button>';    
   document.body.appendChild(divbutton); 
   
}
</script>
</head>
<body>
</body>
</html>

Enjoy Folks

Thursday, April 21, 2016

Our current Train Status System

Step1:

Welcome to designer dairy blog..  Here we are going to look how to apply the  java script conditional

statement for various output

we are going to check

     1. train is running or not ? 
     2. How many trains are available ?
     3. How many trains are running ?
     4. How many trains are not running ?
     5. what are the weekday trains available ?
     6. At what time train is going to start ?

 Step2:

Depending upon  the trainOperational value it will check and satisfied the conditions


var totaltrains = 12

var trainOperational = 8;

//var trainOperational = 12;

var weekday = "friday";


if(trainOperational > 0) {


if(totaltrains == trainOperational)
{
  console.log("All trains are running at the JavaScript Express!");
}

 else {

 for(var trainNumber =1; trainNumber <=totaltrains; trainNumber++)
 {
  
    if(trainNumber<=trainOperational && trainNumber!=3)
     
    {
     
      console.log("Train#" +trainNumber  + " is running");
    }
  
    else if(trainNumber==10 || trainNumber==12 )
    {
      console.log("Train#" +trainNumber  + " is running at noon");
    }
  
    else if(trainNumber==3 && weekday=="friday" )
    {
      console.log("Train#" + trainNumber  + " is running");
    }
  
    else
     
    {
     
      console.log("Train#" + trainNumber  + " is not running");
     
    }
  
 }

}

}
else
{
   console.log("No trains are operational today. Bummer!");
 
}


Step 3:

Enjoy Folks

Wednesday, February 3, 2016

JavaScript Object Oriented Programming(OOP) Tutorial

Object Oriented Programming is one of the most popular ways in programming. Before OOP’s, list of instructions will be executed one by one. But in OOP’s we are dealing with Objects and how those objects interact with one another.


JavaScript Object Oriented Programming(OOPs) Tutorial


JavaScript supports Object Oriented Programming but not in the same way as other OOP languages(c++, php, Java, etc.) do. The main difference between JavaScript and the other languages is that, there are no Classes in JavaScript whereas Classes are very important for creating objects. However there are ways through which we can simulate the Class concept in JavaScript.
Another important difference is Data Hiding. There is no access specifier like (public, private and protected) in JavaScript but we can simulate the concept using variable scope in functions.

Object Oriented Programming Concepts

1) Object
2) Class
3) Constructor
4) Inheritance
5) Encapsulation
6) Abstraction
7) Polymorphism

Preparing the work space

Create a new file "oops.html" and write this code on it. We will write all our JavaScript code on this file.
  1. <html>
  2. <head>
  3. <title>JavaScript Object Oriented Programming(OOPs) Tutorial</title>
  4. </head>
  5. <body>
  6. <script type="text/javascript">
  7. //Write your code here.....
  8. </script>
  9. </body>
  10. </html>

1) Object

Any real time entity is considered as an Object. Every Object will have some properties and functions. For example consider a person as an object, then he will have properties like name, age, etc., and functions such as walk, talk, eat, think, etc. now let us see how to create objects in JavaScript. As mentioned previously there are so many ways to create objects in JavaScript like:
  1. //1)Creating Object through literal
  2. var obj={};
  3. //2)Creating with Object.create
  4. var obj= Object.create(null);
  5. //3)Creating using new keyword
  6. function Person(){}
  7. var obj=new Person();
We can use any of the above way to create Object.

2) Class

As I said earlier there are no classes in JavaScript as it is Prototype based language. But we can simulate the class concept using JavaScript functions.
  1. function Person(){
  2. //Properties
  3. this.name="aravind";
  4. this.age="23";
  5. //functions
  6. this.sayHi=function(){
  7. return this.name +" Says Hi";
  8. }
  9. }
  10. //Creating person instance
  11. var p=new Person();
  12. alert(p.sayHi());

3) Constructor

Actually Constructor is a concept that comes under Classes. Constructor is used to assign values to the properties of the Class while creating object using new operator. In above code we have used name and age as properties for Person class, now we will assign values while creating new objects for Person class as below.
  1. function Person(name,age){
  2. //Assigning values through constructor
  3. this.name=name;
  4. this.age=age;
  5. //functions
  6. this.sayHi=function(){
  7. return this.name +" Says Hi";
  8. }
  9. }
  10. //Creating person instance
  11. var p=new Person("aravind",23);
  12. alert(p.sayHi());
  13. //Creating Second person instance
  14. var p=new Person("jon",23);
  15. alert(p.sayHi());

4) Inheritance

Inheritance is a process of getting the properties and function of one class to other class. For example let’s consider "Student" Class, here the Student also has the properties of name and age which has been used in Person class. So it's much better to acquiring the properties of the Person instead of re-creating the properties. Now let’s see how we can do the inheritance concept in JavaScript.
  1. function Student(){}
  2. //1)Prototype based Inhertance
  3. Student.prototype= new Person();
  4. //2)Inhertance throught Object.create
  5. Student.prototype=Object.create(Person);
  6. var stobj=new Student();
  7. alert(stobj.sayHi());
We can do inheritance in above two ways.

5) Encapsulation

Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data form accessing it outside the scope. For example, In Person class we have Date of Birth (dob) properties which should be protected. Let's see how to do it.
  1. function Person(){
  2. //this is private variable
  3. var dob="8 June 2012";
  4. //public properties and functions
  5. return{
  6. age:"23",
  7. name:"aravind",
  8. getDob:function(){
  9. return dob;
  10. }
  11. }
  12. }
  13. var pobj=new Person();
  14. //this will get undefined
  15. //because it is private to Person
  16. console.log(pobj.dob);
  17. //Will get dob value we using public
  18. //funtion to get private data
  19. console.log(pobj.getDob());
Wrapping up of public and private data into a single data unit is called Encapsulation. The above example is the one that best suites Encapsulation.

6) Abstraction

Abstraction means hiding the inner implementation details and showing only outer details. To understand Abstraction we need to understand Abstract and Interface concepts from Java. But we don't have any direct Abstract or Interface in JS.
Ok! now in-order to understand abstraction in JavaScript lets take a example form JavaScript library JQuery. In JQuery we will use
  1. $("#ele")
to select select an element with id ele on a web page. Actually this code calls negative JavaScript code
  1. document.getElementById("ele");
But we don't need to know that we can happy use the $("#ele") without knowing the inner details of the implementation.

7) Polymorphism

The word Polymorphism in OOPs means having more than one form. In JavaScript a Object, Property, Method can have more than one form. Polymorphism is a very cool feature for dynamic binding or late binding.
  1. function Person(){
  2. this.sayHI=function(){}
  3. };
  4. //This will create Student Class
  5. function Student(){};
  6. Student.prototype=new Person();
  7. Student.prototype.sayHI=function(l){
  8. return "Hi! I am a Student";
  9. }
  10. //This will create Teacher Object
  11. function Teacher(){};
  12. Teacher.prototype=new Person();
  13. Teacher.prototype.sayHI=function(){
  14. return "Hi! I am a Teacher";
  15. }
  16. var sObj=new Student();
  17. //This will check if the student
  18. //object is instance of Person or not
  19. //if not it won't execute our alert code.
  20. if (sObj instanceof Person) {
  21. alert("Hurry! JavaScript supports OOps");
  22. }

Conclusion

JavaScript supports Object Oriented Programming(OOP)Concepts. But it may not be the direct way. We need to create some simulation for some concepts.

Reference website :

http://www.techumber.com/2013/08/javascript-object-oriented-programming-tutorial.html

Monday, August 5, 2013

show and hiding the Elements on Click and Each function



Welcome to Designers Dairy blog here i have posted how to show and hide the selected Elements using

JavaScript in Click and Each function

Step1:


 Script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>

<script type="text/javascript">

$(function()
{
    $('.slider'). each(function() {
       
        $(this).click(function()
       
        {
           
            var Clickeddivid = $(this).attr('data-field');
              
        $('.launchpad').each(function()
       
        {
           
             var visibledivid = $(this).attr('id');
             
           
              if (Clickeddivid == visibledivid)
              {
                 
                  $(this).css('display', 'block');
              }
             
              else
              {
                 
                   $(this).css('display', 'none');
                 
              }
                       
           
        });
       
       
    });   
       
});
   
   
});


</script>



Step2:

 Style:

<style type="text/css">

.display_hide
{
    display:none;
}
</style>




Step3:

Html Code:

<div id="test-1" class="launchpad">
LaunchPad - 1  is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>

<div id="test-2" class="launchpad display_hide">
LaunchPad - 2  is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>

Navigation:

<div class="slider selected_circle"  data-field="test-1"> <a href="#">1</a></div>
<div class="slider select_circle"   data-field="test-2"><a href="#">2</a></div>





 To Added the Rounded Circle or Image in Navigation we have to add


 Script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>

<script type="text/javascript">

$(function()
{
    $('.slider'). each(function() {
       
        $(this).click(function()
       
        {
           

  $('.slider').each (function()
     {

          $(this).addClass('select_circle').removeClass('selected_circle');
        
     });



        var Clickeddivid = $(this).attr('data-field');

              $(this).addClass('selected_circle').removeClass('select_circle');
         
              
        $('.launchpad').each(function()
       
        {
           
             var visibledivid = $(this).attr('id');


             
           
              if (Clickeddivid == visibledivid)
              {
                 
                  $(this).css('display', 'block');
              }
             
              else
              {
                 
                   $(this).css('display', 'none');
                 
              }
                       
           
        });
       
       
    });   
       
});
   
   
});


</script>


Style:

.select_circle
 {
background: url(images/slider_circle.png) no-repeat 0 0;
width:11px;
 height:12px;
cursor:pointer;
}

.selected_circle
{

background: url(images/selected_circle.png) no-repeat 0 0;
 width:12px;
 height:12px; 
 cursor:pointer;
 }




Step4:

Enjoy Folks



Wednesday, July 31, 2013

Hide and show multiple html elements using javascript

 Welcome to Designers Dairy blog here i have posted how to show and hide the selected Elements using

JavaScript dynamically

Step1:

Script:

<script type="text/javascript">
function myfunction(divid,actionid,up,down)
{
     if ($('#' + actionid).hasClass("display_hide"))
     { 
             $('#'+ divid).removeClass('up').addClass('down');           
            $('#'+actionid).removeClass('display_hide').addClass('display_show');
     }

  else
     {
         $('#'+ divid).removeClass('down').addClass('up');
         $('#'+actionid).removeClass('display_show').addClass('display_hide');
           
     }   
 return false; 
 }
</script>

Step2:

Style:

<style type="text/css">
.up
{
    background:url(images/Actionarrowdown.png) no-repeat 0 0;
    height:16px;
    width:16px;
    content: "cccccc"
}


.down
{
    background:url(images/Downarrowblue.png) no-repeat 0 0;   
    width:16px;
    border-color: #337DB2 #337DB2 -moz-use-text-color;
    border-radius: 10px 10px 0 0 !important;
    border-style: solid solid none;
    border-width: 4px 4px 0;
    height: 34px !important;
    margin: 0 !important;
    width: 64px !important;
 
   
   
}
.action_dropdowncontainer {
    border: 4px solid #337DB2;
    font-size: 13px;
    height: auto;
    border-radius:0px 10px 10px 10px !important;
    margin: 0 10px 0 0;
    min-height: 50px;
    padding: 0 0 15px;
    position: absolute;
    width: 205px !important;
    z-index: 10;
}
.display_hide
{
    display:none;
}
.display_show
{
    display:block;
}
</style>

Step3: 

HTML Code :

<div style="height:250px;">

  <div class="up" id="divid-1" onClick="myfunction('divid-1','action_event','up','down')">  </div>

<div id="action_event"  class="dropdownlist actions action_dropdowncontainer border-radius white_bg w186 right display_hide">
                  <div class="action_event_strip"></div>
                  <div class="left"> <a href="#"><i class="icon-large level-1"><b class="left marginleft_33 white_color">1</b></i> <strong class="marginleft_5">View Level 1 </strong> </a></div>
                  <div class="left"> <a href="#"><i class="icon-large level-2"><b class="left marginleft_33 white_color">2</b></i> <strong class="marginleft_5">Request Level 2 </strong> </a></div>
                  <div class="left"><a href="#"> <i class="icon-large callback margintop_5"></i><strong class="paddingleft_8">Callback Pending</strong></a></div>
                  <div class="left"> <a href="#"><i class="icon-large validate left"></i><strong class="alignleft paddingleft_8 margintop_5 w110">Validate</strong></a></div>
                  <div class="left"> <a href="#"><i class="icon-large edit left"></i><strong class="alignleft paddingleft_8 margintop_5">Edit</strong></a></div>
                </div>

</div>



  <div class="up" id="divid-2" onClick="myfunction('divid-2','action_event-1','up','down')">  </div>

<div id="action_event-1"  class="dropdownlist actions action_dropdowncontainer border-radius white_bg w186 right display_hide">
                  <div class="action_event_strip"></div>
                  <div class="left"> <a href="#"><i class="icon-large level-1"><b class="left marginleft_33 white_color">1</b></i> <strong class="marginleft_5">View Level 1 </strong> </a></div>
                  <div class="left"> <a href="#"><i class="icon-large level-2"><b class="left marginleft_33 white_color">2</b></i> <strong class="marginleft_5">Request Level 2 </strong> </a></div>
                  <div class="left"><a href="#"> <i class="icon-large callback margintop_5"></i><strong class="paddingleft_8">Callback Pending</strong></a></div>
                  <div class="left"> <a href="#"><i class="icon-large validate left"></i><strong class="alignleft paddingleft_8 margintop_5 w110">Validate</strong></a></div>
                  <div class="left"> <a href="#"><i class="icon-large edit left"></i><strong class="alignleft paddingleft_8 margintop_5">Edit</strong></a></div>
                </div>

                </div>


 Step4:

Screenshot:




 Click on the Arrow button it will hide the select element and change the arrow up and down


Enjoy Folks

Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...