Skip to main content

Posts

Showing posts with the label JavaScript

Understanding JavaScript: Global Variables vs Variables Inside Document Ready Function

Understanding JavaScript: Global Variables vs Variables Inside Document Ready Function JavaScript is a versatile language used extensively in web development. One common area of confusion for developers is the difference between global variables and variables declared inside the document ready function. This post aims to clarify these concepts and help you understand when to use each. Global Variables in JavaScript Global variables are declared outside of any function, making them accessible from anywhere in your code. Here's an example: var globalVariable = "I am a global variable"; function showGlobalVariable() { console.log(globalVariable); } showGlobalVariable(); // Output: "I am a global variable" In this example, globalVariable is accessible both inside and outside the showGlobalVariable function.

Understanding JavaScript Promises: A Guide for Developers

Understanding JavaScript Promises: A Guide for Developers Hey there, fellow developers! Today, we're diving into the fascinating world of JavaScript Promises. If you've ever been puzzled by how to handle asynchronous operations or tired of callback hell, this guide is for you. We'll cover the basics, how to use Promises effectively, and common pitfalls to watch out for. Let's get started! What is a Promise? In simple terms, a Promise is like a promise in real life. It's something that will either be fulfilled or rejected in the future. In JavaScript, a Promise represents the eventual result of an asynchronous operation. It has three states: Pending: The operation hasn't completed yet. Fulfilled: The operation was successful. Rejected: The operation failed.

HBootstrap Basics: A Simple Guide

Explore Bootstrap basics through a simple HTML setup. Let's create a foundational template: To start, ensure your HTML includes: Proper document structure with <!DOCTYPE html> Basic elements like <html> , <head> , and <body> Viewport meta tag for responsiveness Next, integrate Bootstrap CSS and JavaScript: <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/bootstrap.min.js"></script> With these files added, you're ready to leverage Bootstrap's features. Pro Tip: Ensure your css/bootstrap.min.css and js/bootstrap.min.js files are correctly linked to access Bootstrap's styling and interactive components.

Using JavaScript Image Map

JavaScript can be used to create client-side image maps, which are defined using the <map> and <area> tags in conjunction with the usemap attribute of the <img /> tag. The <map> element acts as a container for defining clickable hotspots within an image. Each <area> tag specifies a shape and coordinates for the hotspot. Below is an example demonstrating how to use an image map with JavaScript to display different messages when hovering over specific areas of an image: <html> <head> <title>Using JavaScript Image Map</title> <script type="text/javascript"> function showTutorial(name) { document.myform.stage.value = name; } </script> </head> <body> <form name="myform"> <input type="text" name="stage" size="20" /> </form> <img src=&quo

Printing Web Pages with JavaScript - Learn How to Implement Print Functionality

Implementing printing functionality on web pages using JavaScript's window.print() function allows users to print the current page directly from the browser. Implementing Print Functionality To enable printing, simply use a button with an onclick event: <input type="button" value="Print" onclick="window.print()" /> This button, when clicked, triggers the browser's print dialog. Making a Page Printer-Friendly A printer-friendly page is optimized for printing, usually with minimal graphics and ads: Create a separate printer-friendly version of the page without unnecessary elements. Alternatively, mark printable content with HTML comments like <!-- PRINT STARTS HERE --> and <!-- PRINT ENDS HERE --> , and use server-side scripts to generate a printable version. Our site follows these practices to provide a better printing e

Client-Side Form Validation with JavaScript

In traditional web forms, validation occurred on the server after submission, leading to delays and server load. JavaScript allows for client-side form validation, checking data before it's sent to the server. Basic Form Validation Basic validation ensures required fields are filled and formats are correct: <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return validate()"> <input type="text" name="Name" /> <input type="text" name="EMail" /> <input type="text" name="Zip" /> <select name="Country"> <option value="-1" selected>[choose yours]</option> <option value="1">USA</option> <option value="2">UK</option> <option value="3">INDIA</option> </select> <input type="submit" val

Types of Errors and Error Handling in JavaScript

Errors in programming can be categorized into three types: Syntax Errors, Runtime Errors, and Logical Errors. Syntax Errors Syntax errors, also known as parsing errors, occur during compilation or interpretation: <script type="text/javascript"> window.print(; // Syntax error: missing closing parenthesis </script> When a syntax error occurs in JavaScript, only the affected thread stops, allowing other threads to continue. Runtime Errors Runtime errors, or exceptions, occur during script execution: <script type="text/javascript"> window.printme(); // Runtime error: calling a non-existing function </script> Exceptions affect the thread they occur in, but other JavaScript threads can continue normally. Logical Errors Logical errors are mistakes in the logic of your script, resulting in unexpected behavior: These errors are not sy

Converting HTML Tables to jqGrid

Converting HTML Tables to jqGrid jqGrid is an excellent jQuery plugin for displaying data in a grid format. One of its useful features is the ability to convert HTML tables into jqGrid, which allows for enhanced user experience and additional functionality. Calling Convention To use the tableToGrid function, ensure that you mark the "Table to Grid" option when you download the grid. The calling convention for the function is: tableToGrid(selector, options) Note: This is a function, not a method. The parameters are: selector (string): Can be either the table's class or id. options (array): An array with grid options. HTML Table Structure The HTML table should have the following structure: <table class="mytab

Persisting jqGrid State with Cookies

Persisting jqGrid State with Cookies jqGrid is an excellent jQuery plugin for displaying a grid. To enhance user experience, we added some filter possibilities and used jQuery to update the URL where data was fetched from. However, when users navigated away from the grid and returned, it would reset to its start position, losing any filtering or sorting they had set. To solve this, we needed to store the user's selections. Here are two JavaScript functions that achieve this using cookies: function saveGridToCookie(name, grid) { var gridInfo = new Object(); name = name + window.location.pathname; gridInfo.url = grid.jqGrid('getGridParam', 'url'); gridInfo.sortname = grid.jqGrid('getGridParam', 'sortname'); gridInfo.sortorder = grid.jqGrid('getGridParam', 'sortorder'); gridInfo.selrow = grid.jqGrid('getGridParam', 'selro

Handling Row Selection in jqGrid with jQuery

Handling Row Selection in jqGrid with jQuery The example below specifies the action to take when a row is selected in a jqGrid: var lastSel; jQuery("#gridid").jqGrid({ ... onSelectRow: function(id) { if(id && id !== lastSel) { jQuery('#gridid').restoreRow(lastSel); lastSel = id; } jQuery('#gridid').editRow(id, true); }, ... }); Explanation This script sets up a jqGrid with a custom action for when a row is selected. Here’s a step-by-step explanation: var lastSel; : A variable to store the last selected row ID. jQuery("#gridid").jqGrid({ ... }); : Initializes the jqGrid on the element with ID gridid . onSelectRow: function(id) { ... } : Defines a function to execute when a row is selected.

Advanced Usage of $(document).ready() in jQuery

Advanced Usage of $(document).ready() in jQuery One more great thing about $(document).ready() that I didn't mention in my previous tutorial is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your JavaScript file with them. It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain-free. Using Multiple $(document).ready() You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready() . So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so: <script src="/scripts/jquery.js"><

Understanding $(document).ready() in jQuery

Understanding $(document).ready() in jQuery To ensure an event works on your page, use the $(document).ready() function. This function loads everything inside it as soon as the DOM is ready, before the page contents are fully loaded. Basic Usage Here's how to use the $(document).ready() function to ensure your jQuery code runs when the document is ready: $(document).ready(function() { // put all your jQuery code here }); Advantages of $(document).ready() The $(document).ready() function has several advantages: Separation of Concerns: Keep your JavaScript/jQuery code in a separate file for better maintainability. Inline JavaScript Avoidance: Avoid adding "behavioral" markup in the HTML, which keeps the HTML cleaner. Multiple Functions: Unlike t

JQGrid Custom Validation - How to Check If Email ID Already Exists in jqGrid

How to Check If Email ID Already Exists in jqGrid Validating whether an email ID already exists is a common requirement in web development. In this guide, we'll show you how to implement this validation in a jqGrid using a custom function. Step 1: Define the Grid Column First, define the column for the email ID in your jqGrid. Add the custom validation rule and specify the custom function: colModel: [ { name: 'emailId', index: 'emailId', width: 200, editable: true, sorttype: 'int', editrules: { email: true, required: true, custom: true, custom_func: checkvalid } } ] Step 2: Implement the Custom Validation Function Next, implement the checkvalid function to check if the email ID already ex

jQuery Drop-Down Menu Example

jQuery Drop-Down Menu Example Have you ever created the drop-down menu using jQuery? No, let's create a simple drop-down menu using jQuery: Step 1: Create the HTML File Create a new file named suckerfish.html and add the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Learn how to create a simple drop-down menu using jQuery. This guide includes a concise code example and clear explanations."> <meta name="keywords" content="jQuery, drop-down menu, JavaScript, web development"> <title>jQuery Drop-Down Menu Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js&q

How to Create a Toggle Effect for a Div with jQuery

jQuery Toggle Effect Example This guide demonstrates how to use jQuery to create a simple toggle effect. The example includes a button to show or hide a div and a link inside the div to close it. Code Example Here’s a straightforward example of how to use jQuery for toggling a div: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Learn how to create a simple toggle effect with jQuery. This guide includes a concise code example and clear explanations."> <meta name="keywords" content="jQuery, toggle, JavaScript, web development"> <title>jQuery Toggle Effect Example</title> <script src="https://co

jQuery Sliding Effects: slideDown, slideToggle, and slideUp

jQuery Sliding Effects: slideDown, slideToggle, and slideUp jQuery provides several methods for creating sliding effects on your web elements. These methods include .slideDown() , .slideToggle() , and .slideUp() . Each of these methods allows you to animate elements with a sliding effect, enhancing the user experience on your website. .slideDown() The .slideDown() method displays the matched elements with a sliding effect. It is used to reveal hidden content with a smooth animation. Example: $('#clickme').click(function() { $('#imageNew').slideDown('slow', function() { // Animation complete. }); }); .slideToggle() The .slideToggle() method is used to either display or hide the matched element with a sliding effect. It toggles the visibility of the element, showing it if it is

Passing User Input to the Server with jQuery AJAX

Passing User Input to the Server with jQuery AJAX Many times, you collect input from the user and pass that input to the server for further processing. jQuery AJAX makes it easy to pass collected data to the server using the data parameter of any available Ajax method. Example This example demonstrates how to pass user input to a web server script, which sends the same result back, and we print it: <html> <head> <title>AJAX Input Example</title> <script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#driver").click(function(event){ var name = $("#name").val(); $("#stage").load(

Handling JSON Responses with jQuery's getJSON()

Handling JSON Responses with jQuery's getJSON() There are situations where a server returns a JSON string in response to your request. The jQuery utility function getJSON() parses the returned JSON string and makes it available to a callback function, which is the first parameter of the function. Syntax Here is the simple syntax for the getJSON() method: [selector]. getJSON(URL, [data], [callback]); Here is the description of all the parameters: URL: The URL of the server-side resource contacted via the GET method. data: An object whose properties serve as the name/value pairs used to construct a query string to be

Loading Data with jQuery AJAX

Loading Data with jQuery AJAX Using jQuery AJAX to load static or dynamic data is very easy. jQuery provides the load() method to accomplish this task efficiently. Syntax Here is the simple syntax for the load() method: [selector]. load(URL, [data], [callback]); Here is the description of all the parameters: URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database. data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. I

jQuery Hello World example

Hello World jQuery Application In this section, we will create our first jQuery application called "Hello World jQuery". This application will simply display Hello World !! (display due to jQuery) message in the browser. After completing this example, you will be able to include the jQuery library in your application and use it to perform simple functions. Let's start developing the Hello World application in jQuery. Setting up jQuery Click on the following link to open a page containing the jQuery library script. This file is around 70KB. Save this as "jquery-1.4.2.js". Now we are ready to use jQuery inside your HTML page. Hello World Example (HelloWorld.html) <htm