A fully accessible and flexible React modal built according WAI-ARIA

A fully accessible and flexible React modal built according WAI-ARIA

A fully accessible and flexible React modal built according WAI-ARIA Authoring Practices.

react-aria-modal

SEEKING CO-MAINTAINERS! Continued development of this project is going to require the work of one or more dedicated co-maintainers (or forkers). If you're interested, please comment in this issue.

A fully accessible and flexible React modal built according WAI-ARIA Authoring Practices.

This module provides a minimally styled "container" component to wrap your fully-styled "presentational" component. It provides the following features, while giving you complete control of the content:

  • Focus is trapped within the modal: Tab and Shift+Tab will cycle through the modal's focusable nodes without returning to the main document beneath.
  • Escape will close the modal.
  • Scrolling is frozen on the main document beneath the modal.
  • When the modal closes, focus returns to the element that was focused just before the modal activated.
  • The dialog element has an ARIA role of dialog (or alertdialog).
  • The dialog element has an ARIA attribute designating its title, either aria-label or aria-labelledby.
  • By default, clicking on the modal's underlay (outside the dialog element) will close the modal (this can be disabled).
  • The modal is appended to the end of document.body instead of its taking up its source-order position within the React component tree.

"Flexible" mostly means that this module provides absolutely minimal inline styles — just enough to get the thing working — but does not provide "complete" modal styling that would get in your way. You get to (have to) style the dialog yourself. (Maybe make a fancy-looking modal module that others could use, which depends on this one behind the scenes?)

Check out the demo.

Project Goals
  • Full accessibility
  • Maximum flexibility
  • Absolutely minimal styling
  • Modular construction: this module is built on top of a few small JS modules that could be used by other React and non-React frontend components:

If you like this kind of module (accessible, flexible, unstyled) you should also check out these projects:

Installation
npm install react-aria-modal

dist/react-aria-modal.js is the Babel-compiled file that you'll use.

React Dependency

Version 2+ is compatible with React >0.14.

Version 1+ is compatible with React 0.13.

Usage

Just provide the right props (see below) and pass the content of the modal as this component's child.

Look in demo/js/ for examples and view the demo, but here's a simple example:

const React = require('react');
const ReactDOM = require('react-dom');
const AriaModal = require('../../');

class DemoOne extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      modalActive: false
    };

    this.activateModal = this.activateModal.bind(this);
    this.deactivateModal = this.deactivateModal.bind(this);
    this.getApplicationNode = this.getApplicationNode.bind(this);
  }

  activateModal = () => {
    this.setState({ modalActive: true });
  };

  deactivateModal = () => {
    this.setState({ modalActive: false });
  };

  getApplicationNode = () => {
    return document.getElementById('application');
  };

  render() {
    const modal = this.state.modalActive
      ? <AriaModal
          titleText="demo one"
          onExit={this.deactivateModal}
          initialFocus="#demo-one-deactivate"
          getApplicationNode={this.getApplicationNode}
          underlayStyle={{ paddingTop: '2em' }}
        >
          <div id="demo-one-modal" className="modal">
            <div className="modal-body">
              <p>
                Here is a modal
                {' '}
                <a href="#">with</a>
                {' '}
                <a href="#">some</a>
                {' '}
                <a href="#">focusable</a>
                {' '}
                parts.
              </p>
            </div>
            <footer className="modal-footer">
              <button id="demo-one-deactivate" onClick={this.deactivateModal}>
                deactivate modal
              </button>
            </footer>
          </div>
        </AriaModal>
      : false;

    return (
      <div>
        <button onClick={this.activateModal}>
          activate modal
        </button>
        {modal}
      </div>
    );
  }
}

ReactDOM.render(<DemoOne />, document.getElementById('demo-one'));
Details

The modal can be activated in a couple of ways:

  • mounting the component without an mounted prop
  • passing true as the mounted prop

Similarly, the modal can be deactivated in a couple of ways:

  • unmounting the component
  • passing false as the mounted prop

Pass your dialog element as the child. And that's it.

When the modal is mounted, you'll notice the following:

  • Focus is trapped: only elements within the modal will receive focus as you tab through. This is done by focus-trap, via focus-trap-react.
  • The modal has the ARIA attributes it needs: a role of dialog (or alertdialog) and an aria-label or aria-labelledby attribute.
  • The main document's scroll is frozen (except on touchscreens). This is done by no-scroll.
  • Your content is set atop a fixed-position underlay. You can control the appearance and behavior of this underlay in various ways (see below).
  • Your content is horizontally centered. You can also vertically center it, if you wish.
  • The modal is appended to document.body, not inserted directly into the HTML source order, as you might assume; but it should still update correctly. (This makes positioning easier (no weird nested z-index troubles).)
Props

Any data-* or aria-* props that you provide will be passed directly to the modal's container <div>.

onExit

Type: Function

This function handles the state change of exiting (or deactivating) the modal. It will be invoked when the user clicks outside the modal (if underlayClickExits={true}, as is the default) or hits Escape (if escapeExits={true}, as is the default), and it receives the event that triggered it as its only argument.

Maybe it's just a wrapper around setState(); or maybe you use some more involved Flux-inspired state management — whatever the case, this module leaves the state management up to you instead of making assumptions. That also makes it easier to create your own "close modal" buttons; because you have the function that closes the modal right there, written by you, at your disposal.

You may omit this prop if you don't want clicks outside the modal or Escape to close it, so don't want to provide a function.

applicationNode

Type: DOM Node

Provide your main application node here (which the modal should render outside of), and when the modal is open this application node will receive the attribute aria-hidden="true". This can help screen readers understand what's going on.

This module can't guess your application node, so you have to provide this prop to get the full accessibility benefit.

getApplicationNode

Type: Function

Same as applicationNode, but a function that returns the node instead of the node itself. This can be useful or necessary in a variety of situations, one of which is server-side React rendering. The function will not be called until after the component mounts, so it is safe to use browser globals and refer to DOM nodes within it (e.g. document.getElementById(..)), without ruining your server-side rendering.

alert

Type: Boolean

If true, the modal will receive a role of alertdialog, instead of its default dialog. The alertdialog role should only be used when an alert, error, or warning occurs (more info).

includeDefaultStyles

Type: Boolean, Default: true

By default, styles are applied inline to the dialog and underlay portions of the component. However, you can disable all inline styles by setting includeDefaultStyles to false. If set, you must specify all styles externally, including positioning. This is helpful if your project uses external CSS assets.

Note: underlayStyle and dialogStyle can still be set inline, but these will be the only styles applied.

dialogClass

Type: String

Apply a class to the dialog in order to custom-style it.

Be aware that, by default, this module does apply various inline styles to the dialog element in order position it. To disable all inline styles, see includeDefaultStyles.

dialogId

Type: String, Default: react-aria-modal-dialog

Choose your own id attribute for the dialog element.

dialogStyle

Type: Object

Customize properties of the style prop that is passed to the dialog.

focusDialog

Type: Boolean

By default, when the modal activates its first focusable child will receive focus. However, if focusDialog is true, the dialog itself will receive initial focus — and that focus will be hidden. (This is essentially what Bootstrap does with their modal.)

See the example below.

initialFocus

Type: String

By default, when the modal activates its first focusable child will receive focus. If, instead, you want to identify a specific element that should receive initial focus, pass a selector string to this prop. (That selector is passed to document.querySelector() to find the DOM node.)

Demo example 3 and an additional example below illustrate a good method if you want no initial visible focus. (Add tabIndex='0' to the modal's content and give it outline: 0;.)

mounted

Type: Boolean

By default, the modal is active when mounted, deactivated when unmounted. However, you can also control its active/inactive state by changing its mounted property instead.

The following two examples are near-equivalents — the first mounts and unmounts, while the second changes the mounted prop:

var MyComponent = React.createClass({
  ..
  render: function() {
    ..
    var modal = (this.state.modalActive) ? (
      <AriaModal onExit={this.myExitHandler}>
        {modalContents}
      </AriaModal>
    ) : false;
    return <div>{modal}</div>;
  },
});

var MyComponentTakeTwo = React.createClass({
  ..
  render: function() {
    ..
    return (
      <div>
        <AriaModal
          mounted={this.state.modalActive}
          onExit={this.myExitHandler}
        >
          {modalContents}
        </AriaModal>
      </div>
    );
  },
});

onEnter

Type: Function

This function is called in the modal's componentDidMount() lifecycle method. You can use it to do whatever diverse and sundry things you feel like doing after the modal activates.

Demo Five, for example, uses it to modify class names and enable some CSS transitions.

titleId

Type: string

The id of the element that should be used as the modal's accessible title. This value is passed to the modal's aria-labelledby attribute.

You must use either titleId or titleText, but not both.

titleText

Type: string

A string to use as the modal's accessible title. This value is passed to the modal's aria-label attribute.

You must use either titleId or titleText, but not both.

underlayStyle

Type: object

Customize properties of the style prop that is passed to the underlay.

The best way to add some vertical displacement to the dialog is to add top & bottom padding to the underlay. This is illustrated in the demo examples.

underlayClass

Type: string

Apply a class to the underlay in order to custom-style it.

This module does apply various inline styles, though, so be aware that overriding some styles might be difficult. If, for example, you want to change the underlay's color, you should probably use the underlayColor prop instead of a class. If you would rather control all CSS, see includeDefaultStyles.

underlayClickExits

Type: boolean, Default: true

By default, a click on the underlay will exit the modal. Pass false, and clicking on the underlay will do nothing.

escapeExits

Type: boolean, Default: true

By default, the Escape key exits the modal. Pass false, and it won't.

underlayColor

Type: string (color value) or false, Default: rgba(0,0,0,0.5)

If you want to change the underlay's color, you can do that with this prop.

If false, no background color will be applied with inline styles. Presumably you will apply then yourself via an underlayClass.

verticallyCenter

Type: boolean

If true, the modal's contents will be vertically (as well as horizontally) centered.

focusTrapPaused

Type: boolean

If true, the modal dialog's focus trap will be paused.

You won't typically need to use this prop. It used to be that the typical reason for pausing a focus trap was to enable nested focus traps; but as of focus-trap v4, the pausing and unpausing of hierachical traps is handled automatically.

focusTrapOptions

Type: object

Customize properties of the focusTrapOptions prop that is passed to the modal dialog's focus trap. For example, you can use this prop if you need better control of where focus is returned.

scrollDisabled

Type: boolean, Default: true

If true, the modal dialog will prevent any scrolling behind the modal window.

AriaModal.renderTo(HTMLElement | string)

react-aria-modal uses react-displace to insert the modal into a new element at the end of <body>, making it easier to deal with positioning and z-indexes.

The static renderTo function returns a new component that renders modals into a specific element, rather than a newly created element at the bottom of the page.

Strings are used as selectors, passed to querySelector.

See demo six for an example.

More examples

An alert dialog that itself receives initial focus (but has no visible outline) and does not exit when the underlay is clicked, and is vertically centered:

var AriaModal = require('react-aria-modal');

var MyModal = React.createClass({
  ..
  render: function() {
    return (
      <AriaModal
        onExit={this.myExitHandler}
        alert={true}
        focusDialog={true}
        titleId='modal-title'
        underlayClickExits={false}
        verticallyCenter={true}
      >
        <div
          style={{ outline: 0 }}
          className='my-modal-dialog'
        >
          <h2 id='modal-title'>Alert!</h2>
          ..
        </div>
      </AriaModal>
    )
  }
})
Contributing & Development

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Lint with npm run lint.

Test the demos with npm start.

Build with npm build.

Download Details:

Author: davidtheclark

Live Demo: http://davidtheclark.github.io/react-aria-modal/demo/

GitHub: https://github.com/davidtheclark/react-aria-modal

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !