var rows = [{
name: 'Jhon',
age: 20,
email: 'jhon@gmail.com'
}, {
name: 'Jack',
age: 50,
email: 'jack@gmail.com'
}, {
name: 'Jim',
age: 35,
email: 'jim@gmail.com'
}];
var html = '<tr border="1|1">';
for (let i = 0; i < rows.length; i++) {
html += '<tr>';
html += '<td>' + rows[i].name + '</td>';
html += '<td>' + rows[i].age + '</td>';
html += '<td>' + rows[i].email + '</td>';
html += '</tr>';
}
html += '</table>';
document.getElementById('box').innerHTML = html;
jQuery Solution
var rows = [{
name: 'Jhon',
age: 20,
email: 'jhon@gmail.com'
}, {
name: 'Jack',
age: 50,
email: 'jack@gmail.com'
}, {
name: 'Jim',
age: 35,
email: 'jim@gmail.com'
}];
$(document).ready(function() {
var html = '<tr border="1|1">';
for (let i = 0; i < rows.length; i++) {
html += '<tr>';
html += '<td>' + rows[i].name + '</td>';
html += '<td>' + rows[i].age + '</td>';
html += '<td>' + rows[i].email + '</td>';
html += '</tr>';
}
html += '</table>';
$('box').html(html);
});
Ready vs Load
document.ready
document.ready will execute right after the HTML document is loded properly, and the DOM is ready.
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("(document).ready was called - document is ready!");
});
window.load
window.load will wait for the page to be fully loaded, this includes inner iframes, images, etc.
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("(window).load was called - window is loaded!");
});
User-Agent Localization
An IP address lookup is a way to get the location of websiate visitors. We usually use public IP lookup services/APIs for this solution. Some of this are paid services and some are free.
Examples include IP Geolocation API, IPinfo and GEOIP DB. They provide the data in various formats as well, such as JSON, XML and CSV.
We'll be using IP Geolocation API for this example.
function ipLookUp() {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log("User\'s Location Data is ", response);
console.log("User\'s Country", response.country);
},
function fail(data, status) {
console.log("Request failed. Return status of ", status);
}
);
}
ipLookUp();
Web Component
Web Components are a set of features that provide a standard component model for the Web[1] allowing for encapsulation and interoperability of individual HTML elements.
Create a custom element
We begin to create the basic structure of our component by creating a rating.js file and inserting the following javascript code inside:
class MyRating extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerText = "Here I am!";
}
}
customElements.define("my-rating", MyRating);
This code allows us to lay the foundation in the creation of what is called a custom element, that is a custom HTML element. A fundamental requirement for the name to be assigned to a custom element to be valid is that it contains a hyphen inside it, as in our example.
The following is a list of expected reactions for a component:
contructor(): While this is not a real custom element reaction, it is important to understand that its code is executed when an instance of the component is created; at this stage it is possible to make state initializations or event handler assignments; however, it is not possible to refer to the DOM
connectedCallback(): This method is invoked whenever an instance of the component is inserted into the DOM; setup operations such as changing the DOM can be performed at this stage
disconnectedCallback(): The method is invoked when the component is removed from the DOM
attributeChangedCallback(): It is executed when an attribute associated with the component is modified; only observed attributes generate the invocation of this method
adoptedCallback(): This method is invoked when the element is adopted from another document via the document.adoptNode() method
Once the component is defined, we can use it in an HTML page as shown by the following example:
In the body of the page we used our component as a normal HTML element.
We point out that it is not possible to use the notation for empty elements for custom elements.
Adding Markup and CSS
Once we have introduced the basic principles on which the definition of a custom element rests, we begin to build the structure of our component by defining its markup and CSS.
We structure our component in such a way as to expose properties that can be manipulated from the outside, through standard getter and setter of javascript class, as shown below:
const styleRules = `
.rating {
color: orange;
}`;
class MyRating extends HTMLElement {
constructor() {
super();
this._maxValue = 5;
this._value = 0;
this.attachShadow({mode: "open"});
}
connectedCallback() {
this.createComponent()
}
get maxValue() {
return this._maxValue;
}
set maxValue(val) {
this._maxValue = val;
this.setAttribute("max-value", val);
}
get value() {
return this._value;
}
set value(val) {
this._value = val;
this.setAttribute("value", val);
}
static get observedAttributes() {
return ["max-value", "value"];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
switch (name) {
case "max-value":
this._maxValue = newValue;
break;
case "value":
this._value = newValue;
break;
}
this.replaceStarList();
}
}
replaceStarList() {
let starNode = this.shadowRoot.children[1];
if (starNode) {
let starList = this.createStarList();
starNode.remove();
this.shadowRoot.appendChild(starList);
}
}
createComponent() {
let style = document.createElement("style");
style.appendChild(document.createTextNode(styleRules));
this.shadowRoot.appendChild(style);
let starList = this.createStarList();
this.appendChild(starList);
}
createStarList() {
let div = document.createElement("div");
let star;
for (let i = 1; i <= this.maxValue; i++) {
if (i <= this.value) {
star = this.createStar("★");
div.appendChild(span);
}
else {
star = this.createStar("☆");
}
div.appendChild(star);
}
return div;
}
createStar(starCode) {
let span = document.createElement("span");
span.setAttribute("class", "rating");
span.innerHTML = starCode;
return span;
}
}
customElements.define("my-rating", MyRating);
With these changes, the initialization code of our component, will have the expected effect, that is, it will make sure that a total of six stars are displayed, two of which are internally colored:
To make our component really useful, let's try to add a little interactivity. We will ensure that the user can express his rating by clicking on one of the stars displayed.
To achieve this, simply change the createStar() function and createStarList() function code as shown below:
createStarList() {
let div = document.createElement("div");
let star;
for (let i = 1; i <= this.maxValue; i++) {
if (i <= this.value) {
star = this.createStar("★", i);
div.appendChild(span);
} else {
star = this.createStar("☆", i);
}
div.appendChild(star);
}
return div;
}
Loader AJAX Call
Display Loading Image or loader when AJAX call is in Progress.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Compare Two Images</h1>
<p>Click and slide the blue slider to compare two images:</p>
<div class="img-comp-container">
<div class="img-comp-img">
<img src="img_snow.jpg" width="300" height="200">
</div>
<div class="img-comp-img img-comp-overlay">
<img src="img_forest.jpg" width="300" height="200">
</div>
</div>
<script>
/* Execute a function that will execute an image compare function for each element with the img-comp-overlay class: */
initComparisons();
</script>
</body>
</html>
CSS
* {
box-sizing: border-box;
}
.img-comp-container {
position: relative;
height: 200px; /* should be the same height as the images */
}
.img-comp-img {
position: absolute;
width: auto;
height: auto;
overflow: hidden;
}
.img-comp-img img {
display: block;
vertical-align: middle;
}
.img-comp-slider {
position: absolute;
z-index: 9;
cursor: ew-resize;
/* set the appearance of the slider: */
width: 40px;
height: 40px;
background-color: #2196F3;
opacity: 0.7;
border-radius: 50%;
}
Javascript
function initComparisons() {
var x, i;
/* find all elements with an "overlay" class: */
x = document.getElementsByClassName("img-comp-overlay");
for (i = 0; i < x.length; i++) {
/* once for each "overlay" element: pass the "overlay" element as a parameter when executing the compareImages function: */
compareImages(x[i]);
}
function compareImages(img) {
var slider, img, clicked = 0, w, h;
/* get the width and height of the img element */
w = img.offsetWidth;
h = img.offsetHeight;
/* set the width of the img element to 50%: */
img.style.width = (w / 2) + "px";
/* create slider: */
slider = document.createElement("DIV");
slider.setAttribute("class", "img-comp-slider");
/* insert slider */
img.parentElement.insertBefore(slider, img);
/* position the slider in the middle: */
slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
/* execute a function when the mouse button is pressed: */
slider.addEventListener("mousedown", slideReady);
/* and another function when the mouse button is released: */
window.addEventListener("mouseup", slideFinish);
/* or touched (for touch screens: */
slider.addEventListener("touchstart", slideReady);
/* and released (for touch screens: */
window.addEventListener("touchend", slideFinish);
function slideReady(e) {
/* prevent any other actions that may occur when moving over the image: */
e.preventDefault();
/* the slider is now clicked and ready to move: */
clicked = 1;
/* execute a function when the slider is moved: */
window.addEventListener("mousemove", slideMove);
window.addEventListener("touchmove", slideMove);
}
function slideFinish() {
/* the slider is no longer clicked: */
clicked = 0;
}
function slideMove(e) {
var pos;
/* if the slider is no longer clicked, exit this function: */
if (clicked == 0) return false;
/* get the cursor's x position: */
pos = getCursorPos(e)
/* prevent the slider from being positioned outside the image: */
if (pos < 0) pos = 0;
if (pos > w) pos = w;
/* execute a function that will resize the overlay image according to the cursor: */
slide(pos);
}
function getCursorPos(e) {
var a, x = 0;
e = (e.changedTouches) ? e.changedTouches[0] : e;
/* get the x positions of the image: */
a = img.getBoundingClientRect();
/* calculate the cursor's x coordinate, relative to the image: */
x = e.pageX - a.left;
/* consider any page scrolling: */
x = x - window.pageXOffset;
return x;
}
function slide(x) {
/* resize the image: */
img.style.width = x + "px";
/* position the slider: */
slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
}
}
}
Adding Print Button to HTML
Adding a Print Button
You can easily add a print button to your web page by adding the following code to your HTML document where you want the button to appear:
onclick="window.print();return false;" />
The button will be labeled as Print this page when it appears on the web page. You can customize this text to whatever you like by changing the text between the quotation marks following:
value=
in the code above.
Adding a Print Link
It's even easier to add a simple print link to your web page. Just insert the following code into your HTML document where you want the link to appear:
print
You can customize the link text by changing "print" to whatever you choose.
Making Specific Sections Printable
You can set up the ability for users to print specific parts of your web page using a print button or link. You can do this by adding a print.ess file to your site, calling it in the head of your HTML document and then defining those sections you want to make easily printable by defining a class.
First, add the following code to the head section of your HTML document:
type="text/css" media="print" />
Next, create a file named print css. In this file, add the following code:
body {
visibility: hidden;
}
.print {
visibility: visible;
}
This code defines all elements in the body as hidden when being printed unless the element has the "print" class assigned to it.
Now, all you need to do is to assign the "print" class to the elements of your web page that you want to be printable.
Anything else on the page that is not assigned to this class will not print.
Enter Key Pressed for Custom Event in HTML formats
The code snippet listens for the Enter key press within the HTML element with the ID form-id. When the Enter key is pressed, it displays an alert message and prevents the form from being submitted. This is often used to handle user input in a specific way or to trigger custom actions when the user presses Enter within a form field.
$(window).ready( function() {
$ ("#form-id").on( "keypress", function(event) {
var keyPressed = event.keyCode || event.which;
if (kevPressed === 13) {
alert ("You pressed the Enter key!!");
event.preventDefault();
return false;
}
});
});
Useful Javascript Console Commands
1. console.log()
The first and most common command is the console.log() command. It takes in a message and prints out the result to the console. It can also print JavaScript objects, arrays - all data types in JavaScript. Additionally, it takes care of formatting the output of the result to make it easier to trace.
The console.log() command is used by developers for most of the things they do - including logging errors to the console. But do you know there is a special console command for that ? It is the console.error() command. It is very similar to the console.log() command except it wraps what you log in a red error box.
console.error("Something is wrong");
3. console.info()
This console command is especial useful to output information to the console. Rather than using console.log(), you will use console.info() to make the information stand out from other console commands.
console.info("You are awesome");
4. console.table()
When dealing with arrays, you usually like to represent it in an easy to understand structure. The console.table() commands handles that for you.
console.table(["orange", "apple", "grape"]);
5. console.assert()
This console command writes an error message to the console if an evaluates condition is false.
console.assert(2 > 3, "It cannot be");
6. console.clear()
This command clears the console for you.
console.clear(); //clears the console
7. & 8. console.group() and console.groupEnd()
These two console commands are useful to group stuff together in the console.
9. console.warn()
Logging warnings in the console should be easy! Thats why the console.warn() command exists.
console.warn("Some warning");
10. & 11. console.time() and console.timeEnd()
There will be times when you will ned to measrue the time taken for an operation to complete. For this situations, you can make use of teh console.time() and console.timeEnd() functions. You use the console.time() to start a timer and console.timeEnd() to stop the timer.
console.time();
for (let i = 0; i < 4; i++) {
console.log("number " + i);
}
console.timeEnd(); // prints time taken since the timer started