Posts

Showing posts with the label JavaScript

Designing a HTML5 game (Snakes and Ladders)

Designing a HTML5 game (Snakes and Ladders) Making of snakes and ladders game Store the positions of start_ladder to end_ladder as a pair Store the positions of start_snake to end_snake as a pair Store the above data in two one-dimensional arrays For example: If the snakes are at positions 4, 9, 17, 35, 44,59,61,78,93] and the ladders start at positions [7,16,92,62], then let arr1 = [4,9,17,35,44,59,61,78,93] ; let arr2 = [7,16,92,62] Write start() function which will initialize the state of the game In this function, do the following tasks. Create a 1000 * 1000 board with 100 boxes, 10 boxes in one row and having alternate colors ("red" and "yellow") Mark the start of a ladder as green color Mark the start of a snake with a black color Assign a number to each box from one to hundred Assign player1 as "white" color Assign playe...

jQuery API - Part 1

jQuery API - Part 1 jQuery has many functions, both synchronous and asynchronous which reduce the task of the programmer and are Efficient Reliable Fast Scalable For getting the immediate ancestor of an element use $("#element_id").parent(); jQuery implements method chaining which means that all jQuery functions that work on a selector process the element and returns the new jQuery variable i.e., $("#element_id") The benefit of jQuery JavaScript library having method chaining is that if you want to perform 10 functions on a single element, it becomes tedious to create 10 new variables assign value to each of them and storing the results in a different variable. So, to get the grandfather of an element, use $("#element_id").parent().parent(); To get / set attributes of an HTML element, use attr() method. Example: If you want the value of the co...

Query Parameters

Query Parameters Query paramaeters are data sent from the client to the server. They area a list of "name" : "value" pairs. They are only relevant in a GET HTTP request. The "name"="value" pair is appended to the ? which is written after the URL. You can incude multiple pairs of name and value separated by a delimiter "&" For example if in a form whose method is GET, if the form is submitted, the URL will look like this: https://www.thwebdesk.blogspot.com/?name1=value1&name2=value2&name3=value3 If the value contains special charcaters that have a certain meaning in a context and encoded to %(2 digit hexadecimal number) For example: If the name = "Gaurav" and value = "S'hirodkar" The HTTP request URL will be https://www.thewebdesk.blogspot.com?name=Gaurav&value=S%3Ehirodkar meaning that the sppecial character apostrophe h...

JavaScript Events

Image
JavaScript Events jQuery plugins are Javascriot file swhich perform specific functions. For example, If we import a datepicker jQuery plugin, We must write $("#date_picker").datepicker({ format:"mm/dd/YYYY") }); Events: There are several events that can happen while browsing a web page. For e.g., User can press a key a user can double click in an element a user enters an section of a web page a user drags an element a user drops an element a user scrolls down or up The syntax for event handlers is as follows: onkeypress onkeydown onkeyup onmouserover onmouseenter onmouseleave ondragover ondrop onscroll onload onbeforeload onunload onbeforeunload ondblclick onsubmit onclick Sometimes, we want to add some...

JavaScript | Regular expressions Advanced

JavaScript | Regular expressions Advanced To implement regular expressions in JavaScript: str.replace(/[0-9]/gi,"a"); If the str contains ab09 , then the above function will return str= abaa Regular expressions are used in pattern matching, i.e., to find if a particular pattren exists in a string. It takes optional parameters 'g' and 'i':- Every regular expression has two properties:- g - It specifies that all the matching characters should be replaced. If g is not specified only the first matching character will be replaced i - The i stands for ignore case i.e., if the regular experession is /[a-c]/i,"d" then the str= "aAbBcC" will be transforemed to Str= "dddddd Both the lowercase and uppercase characters will be transformed. If i is not specified, only the lowercase charcaters will be transformed. for example, if regular expression is /[a-c]/, then the st...

JavaScript | Miscellaneous Topics

JavaScript | Miscellaneous Topics To define a function in JavaScript, use function function_name() { } The for .. in loop:- for(let i in arr) { console.log(i); console.log("<br />"); } To define constant variables in JavaScript use const name = "Gaurav"; The name variable's value cannot be changed. "arguments" variable All JavaScript functions have one implicit object called arguments, which store all the parameters of the function, i.e., arguments[0] will return the first parameter from left to right. arguments.length return the number of arguments passed to the function FormData If we want to send file(s) through AJAX we can use them FormData built-in class of JavaScript. Just write let file_upload = new FormData("<form_name>"); <div class="modal fade" role="dialog"> <div ...

Regular Expressions in JavaScript

Regular Expressions in JavaScript Implemeneting regular expressions in Javascript: use str.replace(/[0-9]/gi,"a"); if th estr contains ab09, then the above function will return str=abaa Every regular expression has two properties:- g - It specifies that all the matching characters should be replaced. If g is not soecified ponly the first matching charcter will be replaced i - The i stands for ignore case i.e.if the regular experession is /[a-c]/i,"d" the the str="aAbBcC" will be transforemed to str= "dddddd" Both the lowercase and upperecase characters will be transformed. If i is not psecified, on.ly the lowercase charcaters will be transformed. for example, if regularn expression in /[a-c]/, the the string will become "dAdBdC" .

JavaScript Arrays | Basics | Events

Image
JavaScript Arrays | Basics An array is an ordered collection of homogeneous elemenets stored in the meory in contiguous locations. All the elements in a Javasritp array should be of the same type. Javascript does not support asociative arrys i.e., arrays containing keys and their rerspective values To create an array, use let arr=new Array(); To set a value for arr[0] = "Gaurav"; arr[1]="Shirodkar" ; To access an array value, use arr[0]; Al;l the elements of the array are stroed in contiguous memory locations and their data type of a elements should be the same. Suppose, I had an array called arr let arr = [0,1,2,3,4,5]; If we want to erxtract a part of an array from 1 to 3, use arr.slice(1,3); To extract vfronm the end of the array, use the '-' sign, for eg, the slice(-2,2) To insert an eleemnt at tyhe of an array, use arr.push(9); The result ...

Timer functions

Timer functions let i=setInterval(function(){ $("div").html("1000");};,3000) }); let j=setTimeout(function(){ $("div").html("1000");};,3000) }); //To stop the timers , we use clearTimeout(j); clearInterval(i); The timer functions are useful if we want to execute a function at different intervals of time, like every 10 seconds or every 1 hour. The most basic use of a timer function is to set a time limit for answwering a question in an online examination,. Another example of a time function is to implement a countdown timer.

Dialog Boxes

Dialog Boxes The modal dialog box is a frame inside. The modal dialog box is a frame inside a web page with two options "OK" and "Cancel" and a close icon at the top right corner. A modal dialog box consists of the following components:- modal_container modal_header(modal_title) modal_body modal_footer To display a dialog box to dispplay a warning or an error message, use the alert() built-in function in Javascript For example, alert("Are you sure to want to exit?"); A alert box consists of two things. A message which is displayed a stext in the dialog box and an ok button on the bottom right corner of the dialog box. prompt() function: To add a response from the client, we add a prompt("<message>","OK","No"); function.

AJAX (Asyncronous JavaScript and XML)

AJAX (Asyncronous JavaScript and XML) AJAX stands for Asynchronous JAvascript and XML in AJAX, we can make requests tyo change the web page contents by small parts and not the complete web page. The class is XMLHTTPRequest let xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { document.getElemntById("demo").innerHTML = this.responseText; } xml.open("GET","ajax_info.txt",true); xml.send(); } To make an ajax call using jQuery, we can write $.ajax({ data: $(document.forms[0]).serialize(), url: "http://www.w3schools.com", method: "GET" }). success(function(response) { $("#result").html(response); }). error(function(error) { $("#result").html(error); });

Data Attributes in HTML

Data Attributes in HTML Data attributes: "data" attributes are normal HTML element attributes and and are defined using the "data-" prefix. To return the list of all the data attributes in jQuery use $("<selector>").data(); Let us take an example: If we want to store different user-defined properties of an HTML element, we can write:- <span id="span1" data-color-blind-style="true" data-should-be-repeated="true" data-repetition-count="3" >Test</span> The following is the jQuery snippet: $(document).ready(function(){ let data_properties = $("#span1").data(); if(data_properties.length != 0) { if(data_properties["color-blind-style"] == "true") { $("#span1").css({color:"red"}); } if(data_properties['should-be-repeated'] == "true") { i...

jQuery Advanced - Part 2

jQuery Advanced - Part 2 Looping over HTML elements let collection = $(".row").each(function() { let x=$(this).html(); return x; }); The above code snippet will store the HTML markup of every element whose class attribute is "row" in collection variable. Sliding items up and down $("#row").slideUp() $("#row").slideUp("slow") $("#row").slideUp(3000) $("#row").slideDown() $("#row").slideDown("slow") $("#row").slideDown(3000) $("#row").slideToggle()

Document Object Model (DOM)

Document Object Model (DOM) The Document Object Model is a storing of the HTML elements and their styles in a tree with the root of the tree being the document object which represents the <html> element. "document.body" represents the <body> element. The window object is an implicit object which represents the tab opened in the browser. For example, "window.document.body" is the same as "document.body"; To access an element by the "id" attribute, use the document.getElementById("<id of the element>") To access elements by the "class" attribute, use the document.getElementsByClassName("<class name of the element(s)>"); To redirect a browser to another web page, use the document.location.href= "http://wwww.example.com" To refresh a web page, use document.location.reload(); To access all the forms in the document,use document.for...

jQuery Advanced - Part 1

jQuery Advanced - Part 1 To hide a paragraph element, $(document). ready(function(){ $("p").load(function(){ $(this).hide(); }); }); To fade HTML element, $("#div1").fadeIn(); :- This fades in an HTML element specified in the jQuery selector $("#div2").fadeIn('slow'); :- This fades in an HTML element specified in the jQuery selector slowly $("#div3").fadeIn(3000); :-This fades in an HTML element specified in the jQuery selector in 3000 milliseconds,i.e., 3 seconds Similarly, To fade out an HTML element on unload of a web page or part of a web page, $("#div1").fadeOut(); :- This fades out an HTML element specified in the jQuery selector $("#div2").fadeOut('slow'); :- This fades out an HTML element specified in the jQuery selector slowly $("#div3").fadeOut(3000); :-This fades out an HTML element specified in the ...

jQuery Events

jQuery Events Events are action points while surfing a web page. A user may click a button for a form submission. Also, a particular user will click a hyperlink and so on. JQuery has built-in functions to handle events. Jquery also has the feature to fire an event from the code. Some Examples: Suppose, I have a login form on my home page as follows: <form action="index.php" method="GET" enctype="application/www-x-urlencoded"> <input type="text" placeholder="Enter username" name="username" /> <input type="password" placeholder="Enter password" name="password" /> <input type="submit" value="Login" /> </form> Suppose I want to store the username in a cookie whenever the user successfully logged in :- we use $(document).ready(function(){ $('form')[0].onSubmit = function() { let name =...

Introduction to jQuery | Basics

Intoduction to jQuery | Basics Jquery is a JavaScript library for writing JavaScript files. The extension of Jquery file is <file_name>.js. The variable which is globally available is the $ variable, You can make AJAX call using jQuery. The syntax is $.ajax() function To access the document object in JQuery, use the $(document) . To add an event handler use the $ (document). ready (function() {}); To add animation we use the animate() method on the CSS selector The $(dollar) function takes a string as an input and the string should abe a valid CSS selector and creates callback fuctions whenevere a method call or callback processing is required. Examples are as follows: $("p.first") This will return all the paragraph (<p>) elements whose class attribute is equal to the value "first". $("#test") This will return the HTML eleemnt whose id attribute is "test"

Sending HTTP headers through Javascript

Sending HTTP headers through Javascript You can send HTTP(Hypertext Transfer Protocol) request headers through javascipt from client to server. For this to accomplish, we need to write a <meta> tag inside the <head> Example: <meta name="http-equiv" content="<one of the below 2 values>" The two values are as follows: 1. content-type => Specifies the character encoding for the document. <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 2. refresh => number in seconds this specifies the number of seconds after which the page will automatically refresh. <meta http-equiv="refresh" content="300" />

Debugging using Javascript

Debugging using Javascript To check the value of variables and return types and many other data, We need to the inspect eleemnt plug-in of the browser. In the Inspect Element window, click on the " Console " tab In most browsers, console is listed as a collection of prompts. All Warnings and error messages are displayed with line numbewr and stack trace These are listed in red colour. Sometimes we may want to check if a variable has a particular value at a particular point in a program or to check if a varible is declared after it is used or if there is an infuinte recursion or an infinite while loop or for loop. For this use the following code: console.log("value of a in function test() is: " + a)