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

Thursday, May 1, 2025

JavaScript If Else, Functions

In programming if and else are conditional statements used to execute different blocks of code based on whether a certain condition is true or false.

if is used to specify a block of code to be executed if a certain condition is true. If the condition is false, the block of code inside the if statement is skipped and the program moves on to the next statement.

For example, if (x > 10) means that the code inside the curly braces {} will be executed only if the value of x is greater than 10.

else is used to specify a block of code to be executed if the if condition is false. If the condition is true, the block of code inside the else statement is skipped and the program moves on to the next statement. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	if (50 == 150) {
		document.write("They are same");
	} else {
		alert("They are different");
	}
		
</script>
	
</body>
</html>

The JavaScript code uses an if-else statement to compare if 50 is equal to 150. Since this condition is false, the code inside the else block is executed, which displays an alert message saying "They are different". The result will be an alert box with the message "They are different" when the HTML file is loaded in a web browser. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	function same() {
		document.write("Number equal to 1000");
	}
	
	function different() {
		document.write("They are different");
	}
	
	var glob_var = 1000;
	
	if (glob_var == 1000) {
		same();
	} else {
		different();
	}
		
</script>
	
</body>
</html>

This JavaScript code defines two functions named same and different. It then declares a global variable glob_var and initializes it to 1000.

The code then checks if the value of glob_var is equal to 1000 using an if statement. If the condition is true, the same function is called and it will print "Number equal to 1000". If the condition is false, the different function is called and it will print "They are different".

In this case, since glob_var is equal to 1000, the same function will be called and it will print "Number equal to 1000".

Using functions to simplify source code is a good programming practice. It makes the code more modular and easier to read, understand, and maintain.

Functions allow you to break down your code into smaller, more manageable pieces, which can be reused in different parts of your program.

This helps to avoid repeating code and reduces the chances of errors or bugs in your code. In addition, functions can make it easier to test your code and make changes to it, since you can test and modify individual functions without affecting the rest of your program.

JavaScript User Agent

The user agent string provided by the browser through the navigator.userAgent property is a useful piece of information that can be used by websites and web applications to provide a better user experience, troubleshoot issues, or track usage statistics.

Here are some common use cases for the user agent string:

  1. Browser and feature detection: Websites can use the user agent string to detect which browser and version the user is using, as well as which features are supported by the browser. This information can be used to customize the website's appearance and functionality based on the user's browser.

  2. Debugging and troubleshooting: Developers can use the user agent string to debug issues reported by users, such as browser compatibility or performance problems. By analyzing the user agent string, developers can identify which browser and version the user is using, and whether the issue is specific to that browser or more general.

  3. Analytics and tracking: Websites can use the user agent string to collect usage statistics, such as the number of users using a particular browser or operating system. This information can be used to optimize the website's performance and improve user experience.

However, it's important to note that the user agent string can be manipulated or spoofed by users, making it less reliable for certain use cases. Additionally, some browsers may provide different user agent strings for different modes or configurations, which can further complicate its use. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	document.write(navigator.appCodeName + "<br>");
	document.write(navigator.product + "<br>");
	document.write(navigator.appVersion + "<br>");
	document.write(navigator.userAgent + "<br>");
	document.write(navigator.platform + "<br>");
	document.write(navigator.language + "<br>");
	document.write(navigator.onLine + "<br>");
	
</script>

</body>
</html>

Within the script block, the code uses the "document.write" method to output the following information about the user's web browser:

  • navigator.appCodeName: The code name of the browser.
  • navigator.product: The name of the browser.
  • navigator.appVersion: The version number of the browser.
  • navigator.userAgent: A string containing the user agent header sent by the browser to the server.
  • navigator.platform: The platform on which the browser is running.
  • navigator.language: The language of the browser.
  • navigator.onLine: A Boolean value indicating whether the browser is currently connected to the internet.

By using these properties, the code can display useful information about the user's browser, such as the browser type and version, the platform it's running on, and whether the user is currently connected to the internet. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	document.write("<h1>I know what you did last summer: <br><br>"
	+ navigator.userAgent+ "</h1>");
	
</script>

</body>
</html>

The code uses the "document.write" method to output an HTML header tag (h1) containing a message and the user agent string. The message says "I know what you did last summer:", followed by two line breaks (br tags).

The "navigator.userAgent" property is a string that contains information about the user agent header sent by the browser to the server. This information can include details about the browser type, version number, and operating system.

By concatenating the user agent string with the message, the code creates a personalized message for the user that includes the details of their browser.

JavaScript Reverse, Push, Sort

Brief explanation of each of these JavaScript array methods:

  • reverse(): This method is used to reverse the order of the elements in an array. It modifies the original array and returns the reversed array.

  • push(): This method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.

  • sort(): This method is used to sort the elements of an array in ascending order by default, or based on a provided comparison function. It modifies the original array and returns the sorted array. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var old_pl = new Array("Cobol", "Fortran", "Algol");
	
	//Reverse
	document.write(old_pl.reverse() + "<br>");
	
	//Push New Elements
	old_pl.push("Basic", "Asembler", "Simula");
	
	document.write("After Push: " + old_pl + "<br>");
	
	//Sort Elements
	old_pl.sort();
	
	document.write("After Sorting: "+ old_pl);
	
</script>
	
</body>
</html>

This script creates an array called old_pl with three elements: "Cobol", "Fortran", and "Algol". Then, three array methods are called on the old_pl array.

The first method is reverse(), which reverses the order of the elements in the old_pl array. The resulting reversed array is output to the webpage using the document.write() method.

The second method is push(), which adds three new elements to the end of the old_pl array: "Basic", "Assembler", and "Simula". The modified array is output to the webpage using the document.write() method.

Finally, the sort() method is called on the old_pl array to sort the elements in alphabetical order. The sorted array is output to the webpage using the document.write() method.

The resulting output of this script would be: 

Algol,Fortran,Cobol
After Push: Algol,Fortran,Cobol,Basic,Assembler,Simula
After Sorting: Algol,Assembler,Basic,Cobol,Fortran,Simula

The first line shows the reversed old_pl array, with the elements in reverse order. The second line shows the old_pl array after the push() method has added the new elements. The third line shows the old_pl array after the sort() method has sorted the elements in alphabetical order.

JavaScript Tutorial

 

  1. JS Introduction
  2. JS Setup, First Script
  3. JS Doctype, Functions
  4. JS Alerts, PopUp Boxes
  5. JS External, Inline JS
  6. JS Comments
  7. JS Variables
  8. JS Data Types
  9. JS Name Rules
  10. JS Functions
  11. JS Function Parameters
  12. JS Multiple Parameters
  13. JS Return Values
  14. JS Functions as Arguments
  15. JS Endless Loop, Infinite
  16. JS Global vs Local
  17. JS Numbers, Math Ops
  18. JS If Statement
  19. JS If Else, Functions
  20. JS If inside If
  21. JS Switch Statement
  22. JS For Loop
  23. JS While Loop
  24. JS Do While Loop
  25. JS Event Handlers
  26. JS On Mouse Over, Out
  27. JS Load, Unload Events
  28. JS Objects
  29. JS Object Creation
  30. JS Object Initialization
  31. JS Arrays
  32. JS Adding Elements, Arrays
  33. JS Concatenation, Arrays
  34. JS Join, Pop Elements
  35. JS Reverse, Push, Sort
  36. JS Prompt Box, User Input
  37. JS Random Numbers
  38. JS Get Window Size
  39. JS Redirects
  40. JS User Agent

Wednesday, April 23, 2025

JavaScript Redirect to Another Site

We can use JavaScript to redirect the user to another site by changing the window.location property to the URL of the new site:


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	function redirect() {
		window.location.assign("https://google.com");
	}
	
</script>

<input type="button" value="To Google"
onclick="redirect();">
	
</body>
</html>

This script defines a JavaScript function called redirect() that uses the window.location.assign() method to redirect the user to the Google homepage.

The window.location.assign() method navigates the browser to the URL specified in its argument, effectively redirecting the user to a new page.

The script also creates an HTML input element with a button type and the text "To Google". When the button is clicked, the onclick attribute calls the redirect() function, which redirects the user to the Google homepage. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body onload="redirect()">

<script>
	
	function redirect() {
		window.location.assign("https://google.com");
	}
	
</script>

</body>
</html>

This code uses the onload event to automatically redirect the user to the Google homepage when the page loads.

The onload event fires when the page has finished loading, so when the user opens the page, the redirect() function is called automatically.

The redirect() function uses the window.location.assign() method to navigate the browser to the URL specified in its argument, which in this case is "https://google.com".

JavaScript Get Window Size

You can get the size of the current window using the window.innerWidth and window.innerHeight properties. These properties return the width and height of the viewport, which is the visible area of the browser window. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var wid = window.innerWidth;
	var hei = window.innerHeight;
	
	document.write("<h1>" + wid + "</h1>");
	document.write("<h1>" + hei + "</h1>");
	
</script>
	
</body>
</html>

This script gets the width and height of the current window using the window.innerWidth and window.innerHeight properties and then displays them as headings using the document.write() method.

When you run this script in a browser, it will display the width and height of the window as headings on the page.

The window.innerWidth and window.innerHeight properties are useful for many purposes in JavaScript, such as:

  1. Responsive web design: You can use these properties to create responsive web designs that adjust to the size of the user's screen.

  2. DOM manipulation: You can use the window size to dynamically adjust the size and position of HTML elements on a page based on the size of the viewport.

  3. Game development: You can use the window size to set the boundaries of a game's playing area or to adjust the game's graphics and controls based on the size of the user's screen.

  4. User experience: You can use the window size to optimize the layout and design of a website or application to provide the best user experience on different devices and screen sizes.

The window.innerWidth and window.innerHeight properties are essential tools for creating dynamic, responsive, and user-friendly web applications in JavaScript.

JavaScript Random Numbers

Random numbers are useful in programming whenever you need to generate unpredictable or random events or data. They can be used to add variability and unpredictability to your applications, as well as to test the robustness of your code. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	//One random number:
	document.write(Math.random() + "<br>");
	
	//Whole Number Generator
	var random_num = (Math.random() * 10);
	var whole_num = Math.round(random_num);
	
	document.write(whole_num);
	
</script>
	
</body>
</html>

This script generates random numbers using the Math.random() method.

The first line of code generates a random number between 0 and 1 using the Math.random() method and outputs it to the webpage using the document.write() method, followed by a line break using the <br> tag.

The second part of the script generates a random whole number between 0 and 10 using the Math.random() method. First, a random number between 0 and 1 is generated using Math.random(), then it is multiplied by 10 to get a random number between 0 and 10. The resulting number is not guaranteed to be a whole number, so the Math.round() method is used to round the number to the nearest integer. Finally, the resulting whole number is output to the webpage using the document.write() method.

When the script is run, it outputs a random number between 0 and 1 and a random whole number between 0 and 10 to the webpage. The Math.random() method is useful for generating unpredictable and random data in JavaScript applications. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	//Generate 10 Whole Random Number
	for (x = 0; x < 10; x = x + 1) {
		document.write(Math.round(Math.random() * 10) + "<br>");
	}
	
</script>
	
</body>
</html>

This script generates 10 random whole numbers between 0 and 10 using a for loop and the Math.random() and Math.round() methods.

Inside the loop, the Math.random() method is used to generate a random number between 0 and 1, which is then multiplied by 10 to get a random number between 0 and 10. The resulting number is not guaranteed to be a whole number, so the Math.round() method is used to round the number to the nearest integer. Finally, each resulting whole number is output to the webpage using the document.write() method, followed by a line break using the <br> tag.

When the script is run, it generates 10 random whole numbers between 0 and 10 and outputs them to the webpage. This script can be useful for generating a random set of data for testing or simulation purposes.

Many programming languages have similar functionality to JavaScript's Math module and random() method for generating random numbers.

For example, Python has a random module which provides functions for generating random numbers, including random() which returns a random floating-point number between 0 and 1. The module also includes functions for generating random integers within a range, shuffling lists, and more.

Similarly, Java has a java.util.Random class which can be used to generate random numbers. The class has methods for generating random integers, floating-point numbers, and more.

Other programming languages such as C++, C#, Ruby, and PHP also provide functionality for generating random numbers and performing mathematical operations.

While the exact syntax and available methods may differ between programming languages, the concepts and functionality are similar across many languages.

JavaScript Prompt Box, User Input

The prompt box displays a message to the user and provides a text field for the user to enter a response. 

Prompt boxes are useful in JavaScript when you need to prompt the user for input data, such as asking for their name, age, or other personal information. Prompt boxes are also commonly used to confirm an action or prompt the user for a yes or no response.

Here are a few examples of where prompt boxes can be used in JavaScript:

  • Collecting user input: You can use a prompt box to ask the user for input data, such as their name, age, or email address.

  • Confirming an action: You can use a prompt box to confirm an action before proceeding, such as deleting a file or closing a window.

  • Validating input: You can use a prompt box to validate user input, such as checking if the user has entered a valid email address or phone number.

  • Customizing user experience: You can use a prompt box to customize the user experience, such as asking the user to choose their preferred language or theme.

Prompt boxes are a simple and effective way to prompt the user for input data and improve the interactivity of your JavaScript applications.


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var grab_stuff = prompt("Your Name: ");
	
	document.write(grab_stuff + "<br>");
	
</script>
	
</body>
</html>

This script displays a prompt box that asks the user to enter their name using the prompt() method. The entered value is stored in the grab_stuff variable.

Then, the entered value is output to the webpage using the document.write() method, followed by a line break using the <br> tag.

When the script is run, it displays a prompt box with a message "Your Name: ", and the user can enter their name into the text field. Once the user clicks "OK", the entered value is stored in the grab_stuff variable and output to the webpage. 


<script>
	
	var grab_stuff = prompt("Your Name: ");
	
	for (x = 0; x < 5; x = x + 1) {
		document.write(grab_stuff + "<br>");
	}
	
</script>

This script displays a prompt box that asks the user to enter their name using the prompt() method. The entered value is stored in the grab_stuff variable.

Then, a for loop is used to output the entered value to the webpage five times using the document.write() method, followed by a line break using the <br> tag. The loop increments the variable x by 1 on each iteration until it reaches a value of 5.

When the script is run, it displays a prompt box with a message "Your Name: ", and the user can enter their name into the text field. Once the user clicks "OK", the entered value is stored in the grab_stuff variable and output to the webpage five times using the for loop. Each time the name is output, it is followed by a line break using the <br> tag.

JavaScript Join, Pop Elements

In JavaScript, join and pop are two methods that can be used on arrays.

join method is used to concatenate all the elements of an array into a string. pop method is used to remove the last element of an array and return that element. It modifies the original array, reducing its length by one. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var old_pl = new Array("Cobol", "Fortran", "Algol");
	
	var new_string = old_pl.join(" ");
	
	document.write(new_string);
	
</script>
	
</body>
</html>

This script creates an array called old_pl with three elements: "Cobol", "Fortran", and "Algol". Then, the join method is called on the old_pl array with a space as the separator argument. The resulting string is assigned to a variable called new_string.

Finally, the document.write method is used to output the new_string to the webpage. The resulting output would be a string that concatenates all the elements of the old_pl array. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var old_pl = new Array("Cobol", "Fortran", "Algol");
	
	document.write(old_pl + "<br><br>");
	old_pl.pop();
	
	document.write(old_pl + "<br><br>");
	old_pl.pop();
	
	document.write(old_pl + "<br><br>");
	old_pl.pop();
	
</script>
	
</body>
</html>

This script creates an array called old_pl with three elements: "Cobol", "Fortran", and "Algol". Then, the document.write method is used to output the old_pl array to the webpage.

After that, the pop method is called on the old_pl array three times in a row, which removes the last element of the array on each call.

After each pop method call, the document.write method is used to output the old_pl array to the webpage again. As a result, the output of the script would be:

Cobol,Fortran,Algol

Cobol,Fortran

Cobol

The first line shows the original array with all three elements. The second line shows the old_pl array after the first pop method call, which removed the last element ("Algol") from the array. The third line shows the old_pl array after the second pop method call, which removed the last element ("Fortran") from the array. The fourth line shows the old_pl array after the third pop method call, which removed the last element ("Cobol") from the array.

At this point, the old_pl array is empty.

JavaScript Concatenation, Arrays

In programming, concatenation refers to the process of combining two or more strings, arrays, or other data structures into a single entity. This can be achieved by using specific operators or methods, depending on the programming language being used. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var old_pl = new Array("Cobol", "Fortran", "Algol");
	var new_pl = new Array("Rust", "Python", "Go");
	
	var all_pl = old_pl.concat(new_pl);
	
	document.write(all_pl + "<br>");
	
	document.write(all_pl[0] + "<br>");
	document.write(all_pl[3] + "<br>");
	document.write(all_pl[5] + "<br>");
	
</script>
	
</body>
</html>

This JavaScript code defines two arrays, old_pl and new_pl, which contain strings representing old and new programming languages, respectively. The concat() method is then used to concatenate the two arrays and return a new array called all_pl. The concatenated array is then printed to the document using document.write(), followed by three examples of accessing elements of the array using square bracket notation ([]).

Concatenation is a very useful operation in programming and is used frequently in various contexts. It is used to combine two or more strings, arrays, or any other type of data structure into a single entity.

For example, in web development, concatenation is commonly used to build dynamic HTML pages by combining various strings, variables, and other data sources. Similarly, in database management, concatenation is used to combine data from multiple tables or records into a single output.

Concatenation can also be used in many other programming contexts, such as text processing, data analysis, and scientific computing.

In JavaScript, concatenation is often used to combine strings. This is particularly useful when working with dynamic text, such as generating messages, building URLs, or creating HTML elements. Concatenation can also be used to join together arrays, as shown in the previous example.

JavaScript provides the + operator for concatenating strings, as well as the concat() method for concatenating arrays. For example: 

var name = "John";
var greeting = "Hello " + name + "!";
console.log(greeting); // Output: "Hello John!"

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = arr1.concat(arr2);
console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]

console.log() is a function in JavaScript used for debugging and logging messages to the console, which is a built-in feature in most web browsers and development environments.

When you call console.log(), it prints the argument passed to it to the console. For example, if you want to log a message to the console, you can use the following code: 

console.log("Hello, world!");

The output will be printed in the console window, which you can usually open by right-clicking on a web page and selecting "Inspect" or "Inspect element", and then navigating to the "Console" tab.

In addition to logging strings, you can also log variables, objects, arrays, and other data types to the console using console.log(). This is a useful tool for debugging and understanding the flow of your code.

JavaScript Adding Elements, Arrays

This script creates a new array called temp and then adds elements to it using the square bracket notation: 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var temp = new Array();
	
	temp[0] = "Prolog";
	temp[1] = "Lisp";
	temp[2] = "C++";
	temp[50] = "Perl";
	
	document.write(temp);	
	
	document.write("<br><br>");
	document.write("If we search for something that's not there:");
	document.write("<br><b>" + temp[25] + "</b>");
	
</script>
	
</body>
</html>

temp[0] = "Prolog" sets the value of the first element to "Prolog".

temp[1] = "Lisp" sets the value of the second element to "Lisp".

temp[2] = "C++" sets the value of the third element to "C++".

temp[50] = "Perl" sets the value of the 51st element to "Perl".

The script then uses document.write to display the entire array. When the array is displayed, you'll notice that there are many empty elements (from index 3 to 49) because they were not explicitly set.

The script then tries to access an element at index 25 (temp[25]) which was not explicitly set, so it will display undefined.

JavaScript Arrays

An array is a special type of object that stores a collection of values of any type (numbers, strings, objects, etc.). Arrays are created using square brackets [] and elements are separated by commas. Each element in an array has an index, which is a numerical value that starts from 0 for the first element, 1 for the second element, and so on. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var plang = new Array("PHP", "Python", "C++", "C");
	
	document.write(plang);
	
</script>
	
</body>
</html>

The code creates an array plang containing four programming languages: "PHP", "Python", "C++", and "C". Then, the code outputs the entire array using the document.write() function. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var plang = new Array("PHP", "Python", "C++", "C");
	
	document.write(plang[0] + "<br>");
	document.write(plang[1] + "<br>");
	document.write(plang[2] + "<br>");
	document.write(plang[3] + "<br>");
	
</script>
	
</body>
</html>

This script uses the document.write() method to output each element of the array on a new line. The [0], [1], [2], and [3] in plang[0], plang[1], plang[2], and plang[3] are called indexes and are used to access each element of the array.

The first element in an array has an index of 0, the second has an index of 1, and so on. In this script, plang[0] is "PHP", plang[1] is "Python", plang[2] is "C++", and plang[3] is "C".

Indexes in JavaScript start from 0 and in most other programming languages.

There are several programming languages where indexes start with 1. Some examples are:

  • MATLAB: MATLAB is a numerical computing environment and programming language used in scientific research, engineering, and other fields. In MATLAB, array indexing starts from 1.

  • FORTRAN: FORTRAN is a high-level programming language used primarily for scientific and engineering applications. In FORTRAN, array indexing also starts from 1.

  • COBOL: COBOL is a business-oriented programming language used in finance, insurance, and other industries. In COBOL, array indexing starts from 1.

However, it's worth noting that many popular programming languages such as C, Java, and Python, use 0-based indexing for arrays and other data structures.

JavaScript Object Initialization

Object initialization in JavaScript refers to the process of creating an object and initializing its properties and values. One common way to initialize an object is by using an object literal, which is a comma-separated list of name-value pairs enclosed in curly braces. For example: 

var person = {
  name: "John",
  age: 30,
  city: "New York"
};

Example:


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	michael = {name: "Michael", lastname: "Smith", ssn: 111222};
	samantha = {name: "Samantha", lastname: "Fox", ssn: 555444};

	document.write(michael.ssn + "<br>");
	
	alert(samantha.name + " "+ samantha.lastname);
	
</script>
	
</body>
</html>

This code initializes two objects, michael and samantha, using object literal notation in JavaScript.

Each object is defined as a set of key-value pairs enclosed in curly braces, where each key represents a property of the object and each value is the corresponding value of that property.

For example, michael has three properties: name, lastname, and ssn, with the corresponding values of "Michael", "Smith", and 111222, respectively. Similarly, samantha has the same properties with different values.

The document.write method is used to output the ssn property of michael, while the alert function displays the name and lastname properties of samantha.

This is a simple way of initializing objects in JavaScript using object literal notation. It is a compact and efficient way of creating objects with properties and values, especially for small and simple objects. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var plang = new Array("PHP", "Python", "C++", "C");
	
	document.write(plang[0] + "<br>");
	document.write(plang[1] + "<br>");
	document.write(plang[2] + "<br>");
	document.write(plang[3] + "<br>");
	
</script>
	
</body>
</html>

The above JavaScript code creates an array named plang containing four elements: "PHP", "Python", "C++", and "C". It then uses the document.write method to output each element of the array to the web page. The array elements are accessed using their indexes, which start at 0. So plang[0] returns the first element of the array ("PHP"), plang[1] returns the second element ("Python"), and so on.

JavaScript Object Creation

In JavaScript, a constructor function is a special type of function that is used to create an object. It is called a constructor because it is used to construct or create objects of a particular type. Constructor functions are defined using the function keyword and have a capitalized name by convention.

Inside the constructor function, the this keyword is used to refer to the object that is being constructed, and properties and methods can be added to the object using dot notation. When a new object is created using the constructor function with the new keyword, the properties and methods are automatically added to the new object. 

When creating objects in JavaScript using a constructor function, we must use the new keyword and the this keyword to ensure that the properties are assigned to the correct instance of the object.

The new keyword creates a new instance of the object and allows us to call the constructor function. Without using the new keyword, the function would simply return undefined.

The this keyword refers to the current instance of the object being created. It allows us to set the value of the properties on the current instance of the object, rather than on the constructor function itself or the global object.


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	function person(name, lastname, ssn) {
		this.name = name;
		this.lastname = lastname;
		this.ssn = ssn;
	}
	
	var michael = new person("Michael", "Smith", 555444);
	var samantha = new person("Samantha", "Fox", 111777);
	
	document.write(michael.name + "<br>");
	document.write(michael.lastname + "<br>");
	document.write(michael.ssn + "<br>");
	
	document.write(samantha.name + "<br>");
	document.write(samantha.lastname + "<br>");
	document.write(samantha.ssn + "<br>");

</script>
	
</body>
</html>

This code defines a constructor function called "person" which takes three parameters: "name", "lastname", and "ssn". Inside the constructor function, "this" keyword is used to refer to the new object being created by the function. The three parameters passed to the function are then assigned as properties of the new object.

The "new" keyword is used to create two new instances of the "person" object, one for Michael and one for Samantha, with their respective names, last names, and social security numbers assigned as properties.

The properties of the objects are then displayed using the document.write() function, by accessing the object's properties using the dot notation, followed by the property name.

JavaScript Objects

An object is a data type that consists of a collection of properties and methods.  

Properties are values that are associated with an object, while methods are functions that are associated with an object.

Properties represent the characteristics of an object, such as its size, color, or name. Properties can be of different data types, including strings, numbers, and arrays.

Methods, on the other hand, represent the actions that can be performed on an object, such as changing its size or color. Methods are usually implemented as functions within the object, and they can also be used to retrieve information from the object or to manipulate its properties.

For example, consider an object representing a car. Properties of the car object could include its make, model, and color, while methods could include starting the engine, stopping the engine, and changing the speed.


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>

<body>

<script>
	
	var person_1 = "Samantha Fox";
	var person_2 = "John Smith";
	
	document.write(person_1.length);
	
	document.write("<br><br>");
	
	document.write(person_2.length);

</script>
	
</body>
</html>

This script creates two variables (think about them as most basic custom object), person_1 and person_2, which store strings representing people's names. It then uses the length property of the string object to determine the number of characters in each name, and displays the results using the document.write() method.

A string is a primitive data type that represents a sequence of characters. However, strings can also be objects, because there is a String object that provides additional properties and methods for working with strings.

When a string is created using the double quotes or single quotes, it is treated as a primitive data type.

This is just introductory way to think about objects in broad sense.

JavaScript Load Events

The JavaScript load event is fired when a web page or a specific element on the page finishes loading. This event is typically used to trigger scripts or functions that depend on the page or element being fully loaded before they can run. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body onload="alert('We are tracking You')">

</body>
</html>

The body element has an "onload" attribute that triggers an alert pop-up message saying "We are tracking You" when the page is fully loaded in the web browser. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->

<script>
function bad_stuff() {
	alert("Something Bad");
}
</script>

</head>

<body onload="bad_stuff()">
	
</body>
</html>

This is an HTML document with a script tag in the head section defining a function named "bad_stuff". The body section has an onload attribute that calls the "bad_stuff" function when the page is loaded, triggering an alert with the message "Something Bad".

It's important to note that this example is purely for educational purposes, and intentionally creating harmful or malicious code is not acceptable.

There have been instances of abuse of the onload event in the past. One example is a technique called "onload abuse" or "onload hijacking", where malicious actors inject JavaScript code into the onload event of a webpage to perform actions without the user's knowledge or consent.

This technique has been used to distribute malware, steal sensitive information, and perform other malicious activities. As a result, many web browsers now have protections in place to prevent this type of abuse, such as blocking or warning users about suspicious onload scripts.

JavaScript On Mouse Over, Out

The onmouseover and onmouseout events are triggered when the user moves the mouse over or out of an element on a web page, respectively.

The onmouseover event is triggered when the mouse pointer moves over an element, such as an image, a link, or a button. It can be used to create interactive effects, such as changing the color of the element or displaying additional information.

The onmouseout event is triggered when the mouse pointer moves out of an element, such as an image, a link, or a button. It can be used to revert the element back to its original state, such as changing the color of the element back to its original color.

Both onmouseover and onmouseout can be used to create interactive and dynamic web pages that respond to user actions, and are commonly used in combination with other JavaScript events and functions to create more complex web page interactions. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<form>

<input type="button" value="Custom: On Mouse Over"
onmouseover="alert('On Mouse Over');">

<br><br><br>

<input type="button" value="Custom: On Mouse Out"
onmouseout="alert('On Mouse Out');">

</form>
	
</body>
</html>

This is an HTML form with two buttons.

The first button has an onmouseover event handler that displays an alert message with the text "On Mouse Over" when the user hovers over the button with the mouse.

The second button has an onmouseout event handler that displays an alert message with the text "On Mouse Out" when the user moves the mouse away from the button. These event handlers are triggered by the corresponding mouse events and execute the specified code when the events occur.

JavaScript Event Handlers

JavaScript event handlers are functions that are triggered in response to a specific event happening in the browser, such as a user clicking on a button, moving their mouse over an element, or typing into a form field.

Event handlers are used to execute code in response to these events and can be added to HTML elements using the "on" attribute or added dynamically using JavaScript.

Examples of commonly used event handlers include "onclick" for when a user clicks on an element, "onmouseover" for when a user moves their mouse over an element, and "onsubmit" for when a user submits a form.


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<form>

<input type="button" value="Click on me for Pop-Up"
onclick="alert('I am from Pop-Up');">

<br><br>

<input type="button" value="Click on me for direct text"
onclick="document.write('Directly on Page');">

</form>
	
</body>
</html>

This code creates a form with two buttons, each with an onclick attribute that triggers a JavaScript event handler function when the button is clicked.

The first button has an onclick attribute with the value alert('I am from Pop-Up');. This means that when the button is clicked, an alert box will pop up on the screen with the message "I am from Pop-Up".

The second button has an onclick attribute with the value document.write('Directly on Page');. This means that when the button is clicked, the text "Directly on Page" will be written directly on the page where the button is located, replacing any existing content. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

function print_stuff() {
	document.write("I am from function");
}

</script>

<form>

<input type="button" value="Click to activate Function"
onclick="print_stuff();">

</form>
	
</body>
</html>

This code creates a function called "print_stuff()" that writes the text "I am from function" to the web page using the document.write() method. It also creates a button in a form that, when clicked, calls the "print_stuff()" function using the onclick attribute.

When the button is clicked, the function is executed and the text "I am from function" is written to the web page.

onclick is an event handler attribute in HTML and JavaScript that specifies the code to be executed when an element, such as a button, is clicked by the user. The code can be a JavaScript function or a script that is executed when the event occurs.

The onclick attribute is commonly used to create interactive web pages, such as triggering a pop-up window, showing a message or changing the content of the web page.

JavaScript Do While Loop

A do-while loop is similar to a while loop, but it will always execute at least once even if the condition is initially false. The loop will continue to execute until the condition becomes false. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	var number = 0;
	
	do {
		document.write("Number atm: " + number + "<br>");
		number = number + 1;
	} while (number < 50);	
		
</script>
	
</body>
</html>

This code initializes a variable called number to 0, and then enters a do-while loop. The loop body consists of a block of code enclosed in curly braces that writes the current value of number to the document and increments it by 1.

The loop will continue to execute as long as number is less than 50.

The main difference between a do-while loop and a while loop is that a do-while loop guarantees that the loop body will be executed at least once, regardless of the initial condition.

JavaScript While Loop

A while loop is a control flow statement that allows a block of code to be repeatedly executed as long as a certain condition is true.

The loop will continue to execute until the condition is no longer true, at which point the program will continue executing the rest of the code following the loop. The condition is checked at the beginning of each iteration of the loop, and if it is true, the code inside the loop is executed. 


<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>

<script>

	var number = 0;
	
	while (number < 100) {
		document.write("Number at this moment: " + number + "<br>");
		number = number + 1;
	}
		
</script>
	
</body>
</html>

The code above shows an example of a while loop in JavaScript. In this case, the loop will continue executing as long as the value of the variable "number" is less than 100.

Inside the loop, the value of "number" is printed to the document using the document.write() function, along with some additional text. After printing the current value of "number", the value of the variable is incremented by 1 using the expression number = number + 1. This is necessary to ensure that the loop eventually terminates.

If a loop is not terminated properly, it will keep running indefinitely, causing what's called an infinite loop. This can be a serious issue, as it can crash the program or even the entire system if the loop consumes too many resources such as CPU or memory. It's important to ensure that loops are properly terminated with a condition that eventually becomes false or a statement that exits the loop when the desired goal is achieved.

Most modern browsers have protection against infinite loops. If a script runs for too long (e.g. due to an infinite loop), the browser will typically show a message asking the user if they want to stop the script. This is done to prevent the browser from becoming unresponsive and to protect against malicious scripts that could potentially crash the browser or execute other harmful actions.

There have been instances where malicious actors have used infinite loops as a form of denial of service attack. In such attacks, the malicious code contains an infinite loop that consumes all available resources of the browser or computer, making it unresponsive or causing it to crash. These attacks are often carried out as part of larger-scale attacks targeting websites or networks. To prevent such attacks, browsers and operating systems have implemented measures to detect and stop scripts that run for too long or consume too many resources.

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...