Learn how to add JavaScript like a Pro

Add JavaScript

In this article, we will discuss how to add JavaScript. we will start from introduction of JavaScript, while the rest of the discussion will focus on various elements that can be add with javascript i.e, How to Add JavaScript to HTML, add an element to a JavaScript array, add a property to object javascript, Add Styles to an Element, and add an event listener in javascript.

how to add JavaScript

JavaScript is a programming language that allows you to accomplish more advanced and high functionality in your survey than would other programming language  be available. 

How to Add JavaScript to HTML

adding javascript to html is very easy even 10th standerd boy can do it. here is an example of adding javascript to html.

there are two ways to add javascript in html

  • Using <script> tags

All you need to do is to go to html webpage >> Edit HTML. and then just start using <script> tag betweeen <body><//body> tag.

example:

<script type='text/javascript'>//<![CDATA[JavaScript Code//]]></script>{codeBox}

  • Host the javascript file externally

in this case, you need to create a javascript file using notepad++ or sub mile text, etc, and then it uploads to the public HTML folder of your hosting account.

<script src='https://example.com/assets/your-javascript.js' type="text/javascript"></script>{codeBox}

How to add an element to a JavaScript array

there are sevral ways to add an element to a javascript array.but we will most common method to add an element to a JavaScript array.

  • Push Method

this is the most common JavaScript array method that will encounter is push(). The push() method is used to add an element to the end of an array.

Let's supposed that you have an array of elements, and each element is a string expressing a task you need to accomplish. It would create sense to add newer items to the end of the array so that we could conclude our earlier tasks first.

const arr = ['1st item', '2nd item', '3rd item'];

arr.push('4th item');

console.log(arr); // ['1st item', '2nd item', '3rd item', '4th item']{codeBox}

  • Unshift Method

Not all tasks are constructed equal. It's the moment to present our buddy unshift() that allows us to add items to the beginning of our array.

const arr = ['1st item', '2nd item', '3rd item'];

const arrLength = arr.unshift('required item item 1', 'required item item 2');

console.log(arrLength); // 5 

console.log(arr); // ['required item item 1', 'required item item 2', '1st item', '2nd item', '3rd item']

{codeBox}

  • Concat Method

If you recognize from above, the unshift() and push() method are return the length of the new array. concat(), on the other hand, will return a completely fresh array.

This is a very important difference and create Concat() extremely useful when you are dealing with arrays you don't want to mutate 

Example


const arr1 = ['?', '?'];

const arr2 = ['?', '?'];

const arr3 = arr1.concat(arr2);

console.log(arr3); // ["?", "?", "?", "?"] 

{codeBox}


How to Add a Class to a Element in JavaScript

Using the className Property:

If you want to adding a class to an element without replacing its existing class, you may do something as shown in the following example:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Add Class to an Element in JavaScript</title>

<style>

    .new1{

        padding: 20px;

        border: 2px solid #ccc;

    }

    .highlight{

        background: green;

    }

</style>

</head>

<body>

    <div class="new1" id="demoDiv">

        <p>This is a demo paragraph of text.</p>

        <button type="button" onclick="addNewClass();">Add Class</button>

    </div>

    <script>

    function addNewClass(){

        // Select div element by its id attribute

        var elem = document.getElementById("demoDiv");

        elem.className += " highlight";

    }

</script>

</body>

</html>{codeBox}


how to add property to object javascript

There are several ways to add properties to an object in JavaScript. First, one way is to add a property utilizing the dot notation:

obj.foo = 1; {codeBox}

We added the foo property to the obj object above with value 1.

We can even add a property by utilizing the bracket notation:

obj['foo'] = 1;

{codeBox}

It does the exact thing as the first example, but we can have invalid property identifiers in the string.

So, we can write something like:

obj['foo-bar'] = 1;{codeBox}


var obj = { Name: "Ram" };

obj.Age = 24;

console.log(obj.Age)

obj['Country'] =  "IND"

console.log(obj.Country)

In the example above, the 

{codeBox}


How to Add Styles to an Element

Here we are discuss how to add styles to an element using JavaScript DOM methods.

Let us consider that you have an <div> element as follows:

<div class="note">JavaScript and CSS</div>

{codeBox}

And you desire to add styles to this element. By applying the JavaScript DOM methods, you can add the inline styles or global styles to elements.

  • Inline styles

you follow these steps to add inline styles to an element

First, choose the element by using DOM methods such as document.querySelector(). The chosen element has the style property that allows you to set the different styles to the element.

Then, put the values of the properties of the style object.

The subsequent code transforms the background color and color of the <div> element above:

const note = document.querySelector('.note');

note.style.backgroundColor = 'green';

note.style.color = 'blue';

{codeBox}

1.Using cssText property

Adding unique style is quite lengthy. Fortunately, you can add a set of multiple styles at once by using the cssText property:

note.style.cssText += 'color:blue;background-color:green';

{codeBox}

For example, here we used the += operator to append new styles to the existent ones. If you use the = operator, the existing style will be terminated, like this:

note.style.cssText = 'color:blue;background-color:green';

{codeBox}

2.Using a helper function

The following helper function which is given below accepts an element and a style object. It adds all the essential styles from the style object to the style property of the element:

function css(element, style) {

    for (const property in style)

        element.style[property] = style[property];

}

{codeBox}

And you may use this CSS() helper function to set the styles for the <div> element as observed:

const note = document.querySelector('.note');

css(note, {

    'background-color': 'green',

    color: 'blue'

});

{codeBox}

  • Global Styles

here we discuss adding the global styles to an element, creating the style element, loading it with the CSS rules, and appending a style element to the DOM tree, like this:

const style = document.createElement('style');

style.innerHTML = `

      .note {

        background-color: green;

        color:blue;

      }

    `;

document.head.appendChild(style);

{codeBox}

how to add event listener in javascript

An event is the most important part of JavaScript.A web page reacts according to an event that occurred. Some events are user-generated, some are generated by API’s. An event listener is a process in JavaScript that defers an event to occur. A simple example of an event is a user clicking the mouse or pressing any key on the keyboard.

syntax

element.addEventListener(event, listener, useCapture);

{codeBox}

Parameters: 

  • event: event may be any valid JavaScript event. Events are used without the “on” prefix like use “click” rather of “on click” or “mousedown” rather of “onmousedown”.
  • listener(handler function): It may be a JavaScript function that responds to the event that occurs.
  • useCapture: It is an extra parameter used to control event propagation. A boolean value passed where “true” denotes capturing phase and “false” denotes the bubbling phase.

Example JavaScript Code to show the working of addEventListener() method : 

<!DOCTYPE html>

<html>

<body>

    <button id="New_Try">Click here</button>

    <h1 id="New_Text"></h1>

    <script>

    document.getElementById("New_Try").addEventListener("click", function(){

    document.getElementById("New_Text").innerNew_Text = "Blogs_afrique";

});

    </script>

</body>

</html>

{codeBox}

I hope this article will help you understand how to add javascript to various elements  

*

Post a Comment (0)
Previous Post Next Post