Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Events in JavaScript

Posted in Javascript, javascript interview questions

Custom-events

In JavaScript, there are number of built in events like click, mouseover, submit, scroll etc. There are some drawbacks with these built in browser events. They works only with DOM elements.

Here is an example of click event:

document.addEventListener('click', function(event) {
  
    alert('Button Clicked');
  
});

Above code works with DOM element such as div, button, anchor tag where click event is attached. This is useful when you want a user to perform some action on your web page.
But you can create your custom events in JavaScript. JavaScript provides a way to create and dispatch a custom events as shown below.

var myDialogEvent = new CustomEvent("showDialog", {
    cancelable: true,
    detail: {
          desc: "Display alert message with custom text",
          time: new Date(),
    }
});

Create a CustomEvent object and pass the details about the events. However, detail and cancelable parameters are optional. You can pass empty object to the newly created custom event object.

var myDialogEvent = new CustomEvent("showDialog", {});

cancelable: true means events can be cancelled using event.stopPropagation.
In the detail you can mentioned some description about the event.

Dispatch Event

You can dispatch the event using window.dispatchEvent

 window.dispatchEvent(myDialogEvent);

The ‘myDialogEvent’ gets triggered once you dispatch it. It’s time to create a listener for your custom event. Listening for a custom event you just created is similar to adding a listener for DOM events.

window.addEventListener('showDialog', function(event) {
    if (event.detail) {
        alert(event.detail.desc);
    }
});

Once the event is triggered above code handle the ‘showDialog’ event and display an alert with the event description.

Use custom events if you are creating any JavaScript library or framework for your projects. If you have used any JavaScript framework like React or Angular with JQuery it custom events would be a good choice for communicating any Angular or React component with JQuery code.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Get URL parameters using JavaScript

Posted in Javascript, javascript interview questions

Sometimes you might need to get URL parameters also called as query string parameters using JavaScript. URL parameters can be one or multiple.

Example:

http://localhost/mypage?id=10

Multiple URL parameters:

http://localhost/mypage?id=10&name=Simy

Use script below to get URL parameters:


function getURLParameter(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

Above function returns specified URL parameter based on the argument supplied to that function.

getURLParameter(“id”) –> Returns 10

getURLParameter(“name”) –> Returns Simy

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Document Object Model (DOM)

Posted in Javascript, javascript interview questions, JQuery, Jquery interview questions

DOM is a hierarchy of HTML tags. It represents arrangement of HTML tags in a web page. The DOM provides the information needed for JavaScript to communicate with the elements on the web page. The DOM also provides the tools necessary to navigate through, change, and add to the HTML on the page.

HTML Document:
HTML document

The above HTML document can be represented in the form of a document tree which is called “document object model” is shown below. Each leaf on the tree is called as node which directly relates to each element on a page. When a node appears inside another node of a tree it is considered as a child node of that node.

Structure of DOM:
DOM

JavaScript provide several ways to select DOM elements, change style of the elements, remove element from DOM, add elements to DOM.

How Do I Access the DOM?

To access DOM elements use JavaScript in-built functions.

Example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id=" header">This is header</h1>
<script>
  var x=document.getElementById("header");
  alert(x.innerHTML);
</script>

</body>
</html>

There are several document functions to select DOM elements like document.getElementsByTagName(), document.createElement(“div”) etc.

Problem with JavaScript Selectors:

To select DOM elements using JavaScript, developers need to write huge code. JQuery solves these problems and provides easy-to-use, cross-browser compatible ways of selecting and working with page elements. We can use JQuery Selectors to modify above code. JQuery reduces developer’s efforts to select and perform any operation on DOM elements.

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
  alert($("#header").html());
});
</script>

</head>
<body>
<h1 id=" header">This is header</h1>
</body>
</html>

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Date object in JavaScript

Posted in Javascript, javascript interview questions

date-in-javascript

Date() is an object in JavaScript. Date methods are used to find current day, current year also it is used to set value of year, month, date.

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date;
</script>

Above example will display current date and time in below format.
Sat Nov 28 2015 06:23:43 GMT-0800 (Pacific Standard Time

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date.toDateString();
</script>

toDateString() is used to display date in short format without time.
Sat Nov 28 2015

Methods:

getDate():
Display date as number.

getDay():
Display weekday as number.

getFullYear():
Display Full year in YYYY format.

getMonth():
Display month as number. JavaScript counts month from 0-11. Refer below example

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date.getMonth();
</script>

If current month is November then value of dateText will be 11. If you want to display day as text the create an array of day’s and accordingly display day values as string.

Example:

        var d=new Date();
	var weekday=new Array(7);
	weekday[0]="Monday";
	weekday[1]="Tuesday";
	weekday[2]="Wednesday";
	weekday[3]="Thursday";
	weekday[4]="Friday";
	weekday[5]="Saturday";
	weekday[6]="Sunday";
        var n = weekday.indexOf[d.getDay()];

Above code returns current day as string.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Difference between undefined and null in JavaScript

Posted in Javascript, javascript interview questions

undefined means value is not assigned to a variable while null is a value which can be assigned to variables. null is a reserved keyword in JavaScript while undefined is a built in object in JavaScript.

Example:

  var a;
  console.log("Value of a is: "+ a);

Above statement will return “Value of a is undefined” because variable a is just declared and value of the variable a is not defined yet.

  var a=null;
  console.log("Value of a is: "+ a);

Now, we are assigning a “null” value to variable a. Above statement will return null value in console.