Jquery
AJAX = Asynchronous JavaScript and XML.
DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
Interview Question
https://career.guru99.com/top-50-jquery-interview-questions/
Automatically Refresh or Reload Page using SetInterval() Method
In the second example, I am using the SetInterval() method to call the .reload() function.
<script>
$(document).ready(function() {
// Call refresh page function after 5000 milliseconds (or 5 seconds).
setInterval('refreshPage()', 5000);
});
function refreshPage() {
location.reload();
}
</script>
Jsonp:
Jquery ajax by default use XMLHttpRequest .
it works in same origin policy but not work for if origin is different.
so in this case we have need to create a
XMLHttpRequest cannot load http://external-domain/service. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://my-domain’ is therefore not allowed access.
var script = $("<script />", {
src: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
type: "application/json"
}
);
$("head").append(script);
References: https://www.sitepoint.com/jsonp-examples/
//------Jsonp----------
JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data.
So we can load json from different origin.
$.ajax({
url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
dataType: "jsonp"
});
Jquery:
DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
Interview Question
https://career.guru99.com/top-50-jquery-interview-questions/
Automatically Refresh or Reload Page using SetInterval() Method
In the second example, I am using the SetInterval() method to call the .reload() function.
<script>
$(document).ready(function() {
// Call refresh page function after 5000 milliseconds (or 5 seconds).
setInterval('refreshPage()', 5000);
});
function refreshPage() {
location.reload();
}
</script>
setInterval(function() {
window.location.reload();
}, 300000);
Jsonp:
Jquery ajax by default use XMLHttpRequest .
it works in same origin policy but not work for if origin is different.
so in this case we have need to create a
<script>
tag, set the src
attribute to that of our JSON file and inject it into the page.XMLHttpRequest cannot load http://external-domain/service. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://my-domain’ is therefore not allowed access.
var script = $("<script />", {
src: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
type: "application/json"
}
);
$("head").append(script);
References: https://www.sitepoint.com/jsonp-examples/
//------Jsonp----------
JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data.
So we can load json from different origin.
$.ajax({
url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
dataType: "jsonp"
});
Jquery:
Query is a fast, lightweight, and feature-rich JavaScript library that is based on the principle "write less, do more". It's easy-to-use APIs makes the things like HTML document traversal and manipulation, event handling, adding animation effects to a web page much simpler that works seamlessly across all the major browsers like Chrome, Firefox, Safari, Internet Explorer, etc.
jQuery also gives you the ability to create an Ajax based application in a quick and simple way.
jQuery was originally created by John Resig in early 2006. The jQuery project is currently run and maintained by a distributed group of developers as an open-source project.
- select elements to perform manipulation.
- create effect like show or hide elements, sliding transition, and so on.
- create complex CSS animation with fewer lines of code.
- manipulate DOM elements and their attributes.
- implement Ajax to enable asynchronous data exchange between client and server.
- traverse all around the DOM tree to locate any element.
- perform multiple actions on an element with a single line of code.
- get or set dimensions of the HTML elements.
Advantages of Using jQuery :
- Save lots of time — You can save lots of time and efforts by using the jQuery inbuilt effects and selectors and concentrate on other development work.
- Simplify common JavaScript tasks — jQuery considerably simplifies the common JavaScript tasks. Now you can easily create feature rich and interactive web pages with fewer lines of codes, a typical example is implementing Ajax to update the content of a page without refreshing it.
- Easy to use — jQuery is very easy to use. Anybody with the basic working knowledge of HTML, CSS and JavaScript can start development with jQuery.
- Compatible with browsers — jQuery is created with modern browsers in mind and it is compatible with all major modern browsers such as Chrome, Firefox, Safari, Internet Explorer, etc.
- Absolutely Free — And the best part is, it is completely free to download and use.
CDN (Content Delivery Network) : Google and Microsoft/Jquery
The Document Ready Event :
// jQuery methods go here...
});
we can also used below function:
<script type="text/javascript">
$(function(){
// Some code to be executed...
alert("Hello World!");
});
</script>
Jquery Action:
jQuery statements to perform any action following the basic syntax, like:
The Document Ready Event :
- The
$(document).ready(handler);
— This statement is typically known as ready event. Where the handler is basically a function that is passed to theready()
method to be executed safely as soon as the document is ready to be manipulated i.e. when the DOM hierarchy has been fully constructed.
// jQuery methods go here...
});
we can also used below function:
<script type="text/javascript">
$(function(){
// Some code to be executed...
alert("Hello World!");
});
</script>
Jquery Action:
jQuery statements to perform any action following the basic syntax, like:
$(selector).action();
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s);
Selecting Elements by ID
$("#mark").css("background", "yellow");
Selecting Elements by Class Name
$(".mark").css("background", "yellow");
Selecting Elements by Name
$("p").css("background", "yellow");
Selecting Elements by Attribute
$('input[type="text"]').css("background", "yellow");
Selecting Elements by Compound CSS Selector
// Highlight only paragraph elements with class mark
$("p.mark").css("background", "yellow");
// Highlight only span elements inside the element with ID mark
$("#mark span").css("background", "yellow");
// Highlight li elements inside the ul elements
$("ul li").css("background", "red");
jQuery Custom Selector
// Highlight table rows appearing at odd places
$("tr:odd").css("background", "yellow");
// Highlight table rows appearing at even places
$("tr:even").css("background", "orange");
// Highlight first paragraph element
$("p:first").css("background", "red");
What are Events:
An event represents the precise moment when something happens.
Events are often triggered by the user's interaction with the web page, such as when a link or button is clicked, text is entered into an input box or textarea, selection is made in a select box, key is pressed on the keyboard, the mousepointer is moved etc. In some cases,
the Browser itself can trigger the events, such as the page load and unload events.
Commonly Used jQuery Event Methods :
$(document).ready() :
The $(document).ready() method allows us to execute a function when the document is fully loaded.
click():
$("p").click(function(){
$(this).hide();
});
dblclick():
mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
mouseleave():
The function is executed when the mouse pointer leaves the HTML element:
mousedown():
The function is executed, when the left, middle or right mouse button is pressed down,
while the mouse is over the HTML element:
mouseup():
The function is executed, when the left, middle or right mouse button is released,
while the mouse is over the HTML element:
hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and
the second function is executed when the mouse leaves the HTML element:
focus():
The function is executed when the form field gets focus:
The on() Method :
The on() method attaches one or more event handlers for the selected elements.
Questions:
.attr() calls .prop() internally so the .attr() method will be slightly slower than accessing them directly through .prop().
$("img").before("Some text before");
$("body").append(txt1, txt2, txt3); // Append the new elements
reference:https://www.w3schools.com/jquery/jquery_css_classes.asp
$("h1, h2, p").removeClass("blue");
$("#div1").addClass("important blue");
$("h1, h2, p").toggleClass("blue");
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s);
$(this).hide()
- hides the current element.$("p").hide()
- hides all <p> elements.$(".test").hide()
- hides all elements with class="test".$("#test").hide()
- hides the element with id="test".
JQuery Selectors :
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name,
id, classes, types, attributes, values of attributes and much more.
The element Selector
The jQuery element selector selects elements based on the element name.
$("p") Selecting Elements by ID
$("#mark").css("background", "yellow");
Selecting Elements by Class Name
$(".mark").css("background", "yellow");
Selecting Elements by Name
$("p").css("background", "yellow");
Selecting Elements by Attribute
$('input[type="text"]').css("background", "yellow");
Selecting Elements by Compound CSS Selector
// Highlight only paragraph elements with class mark
$("p.mark").css("background", "yellow");
// Highlight only span elements inside the element with ID mark
$("#mark span").css("background", "yellow");
// Highlight li elements inside the ul elements
$("ul li").css("background", "red");
jQuery Custom Selector
// Highlight table rows appearing at odd places
$("tr:odd").css("background", "yellow");
// Highlight table rows appearing at even places
$("tr:even").css("background", "orange");
// Highlight first paragraph element
$("p:first").css("background", "red");
What are Events:
An event represents the precise moment when something happens.
Events are often triggered by the user's interaction with the web page, such as when a link or button is clicked, text is entered into an input box or textarea, selection is made in a select box, key is pressed on the keyboard, the mousepointer is moved etc. In some cases,
the Browser itself can trigger the events, such as the page load and unload events.
Commonly Used jQuery Event Methods :
$(document).ready() :
The $(document).ready() method allows us to execute a function when the document is fully loaded.
click():
$("p").click(function(){
$(this).hide();
});
dblclick():
mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
mouseleave():
The function is executed when the mouse pointer leaves the HTML element:
mousedown():
The function is executed, when the left, middle or right mouse button is pressed down,
while the mouse is over the HTML element:
mouseup():
The function is executed, when the left, middle or right mouse button is released,
while the mouse is over the HTML element:
hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and
the second function is executed when the mouse leaves the HTML element:
focus():
The function is executed when the form field gets focus:
The on() Method :
The on() method attaches one or more event handlers for the selected elements.
Questions:
What is the difference between find and children methods?
Find method is used to find all levels down the DOM tree but children find single level down the DOM tree.
What is the use of each function in jQuery?
Each function is used to iterate each and every element of an object. It is used to loop DOM elements, arrays and the object properties.
What is the difference between size and length of jQuery?
Size and length both returns the number of element in an object. But length is faster than the size because length is a property and size is a method.
Can we add more than one ‘document.ready’ function in a page?
Yes, we can add more than one document.ready function in a page. But, body.onload can be added once in a page.
What is the use of jQuery load method?
jQuery load method is a powerful AJAX method which is used to load the data from a server and assign the data into the element without loading the page.
Whether our own specific characters are used in place of $ in jQuery?
Yes, We can use our own variable in place of $ by using the method called no Conflict () method.
var sample = $.noConflict()
jQuery Filters
Use jQuery to filter/search for specific elements.
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});</script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});</script>
JQuery Callback Functions
A callback function is executed after the current effect is finished.
Typical syntax: $(selector).hide(speed,callback);
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
jQuery - Chaining :
Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
A callback function is executed after the current effect is finished.
Typical syntax: $(selector).hide(speed,callback);
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
jQuery - Chaining :
Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
Get Attributes - attr()
The jQuery attr() method is used to get attribute values.
alert($("#w3s").attr("href"));
The jQuery attr() method is used to get attribute values.
alert($("#w3s").attr("href"));
The jQuery
$("#w3s").attr("href", "https://www.w3schools.com/jquery/");
Difference between Property and attribute
The property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for HTML attributes since they are strictly defined. The attribute tells you nothing about the current state.
The Prop() method returns a Boolean value for checked, selected, disabled, readOnly and so on while attr returns a defined string. So, you can directly use .prop("checked") in an if condition.attr()
method is also used to set/change attribute values.$("#w3s").attr("href", "https://www.w3schools.com/jquery/");
Difference between Property and attribute
The property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for HTML attributes since they are strictly defined. The attribute tells you nothing about the current state.
- for a checkbox (jquery 1.6+)
- <input id="check1" checked="checked" type="checkbox" />
- .attr('checked') //returns checked
- .prop('checked') //returns true
- .is(':checked') //returns true
.attr() calls .prop() internally so the .attr() method will be slightly slower than accessing them directly through .prop().
Add New HTML Content
We will look at four jQuery methods that are used to add new content:
append()
- Inserts content at the end of the selected elementsprepend()
- Inserts content at the beginning of the selected elementsafter()
- Inserts content after the selected elementsbefore()
- Inserts content before the selected elements
$("img").before("Some text before");
$("body").append(txt1, txt2, txt3); // Append the new elements
reference:https://www.w3schools.com/jquery/jquery_css_classes.asp
Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods:
remove()
- Removes the selected element (and its child elements)empty()
- Removes the child elements from the selected element
$("#div1").remove();// child and itself
$("#div1").empty();//only remove child
jQuery Manipulating CSS
jQuery has several methods for CSS manipulation. We will look at the following methods:
addClass()
- Adds one or more classes to the selected elementsremoveClass()
- Removes one or more classes from the selected elementstoggleClass()
- Toggles between adding/removing classes from the selected elementscss()
- Sets or returns the style attribut
$("#div1").addClass("important blue");
$("h1, h2, p").toggleClass("blue");
jQuery css() Method
The
css()
method sets or returns one or more style properties for the selected elements.
$("p").css("background-color");// return value
$("p").css("background-color", "yellow"); // set value
jQuery Dimension Methods
jQuery has several important methods for working with dimensions:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
jQuery Traversing :
jQuery Traversing - Ancestors :
Traversing Up the DOM Tree
Three useful jQuery methods for traversing up the DOM tree are:
parent()
parents()
parentsUntil()
The
parent()
method returns the direct parent element of the selected element.
$("span").parent();
The
parents()
method returns all ancestor elements of the selected element, all the way up to the document's root
$("span").parents();
$("span").parents("ul"); /search for ul parents
The
parentsUntil()
method returns all ancestor elements between two given arguments.
$("span").parentsUntil("div");
Traversing Down the DOM Tree(Descendants)
Two useful jQuery methods for traversing down the DOM tree are:
children()
find()
The
$("div").children();
The
$("div").find("span"); //return all span child
children()
method returns all direct children of the selected element.$("div").children();
The
find()
method returns descendant elements of the selected element, all the way down to the last descendant.$("div").find("span"); //return all span child
jQuery Traversing - Siblings :
here are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
The
siblings()
method returns all sibling elements of the selected element.
$("h2").siblings();
$("h2").siblings("p");//specific
The
next()
method returns the next sibling element of the selected element.
$("h2").next();
The
nextAll()
method returns all next sibling elements of the selected element.
The
nextUntil()
method returns all next sibling elements between two given arguments.
$("h2").nextUntil("h6");
jQuery prev(), prevAll() & prevUntil() Methods
The
prev()
, prevAll()
and prevUntil()
methods work just like the methods above but with reverse functionality.The first(), last(), eq(), filter() and not() Methods
The
The
$("div").last();
The
The
The
first()
method returns the first element of the specified elements.The
last()
method returns the last element of the specified elements.$("div").last();
The
eq()
method returns an element with a specific index number of the selected elements.The
filter()
method lets you specify a criteria. The
not()
method returns all elements that do not match the criteria.jQuery load() Method
The jQuery
load()
method is a simple, but powerful AJAX method.
The
load()
method loads data from a server and puts the returned data into the selected element.
$("#div1").load("demo_test.txt");
jQuery $.get() Method
The
$.get()
method requests data from the server with an HTTP GET request.
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
alert("Data: " + data + "\nStatus: " + status);
});
jQuery $.post() Method
The
$.post()
method requests data from the server using an HTTP POST request.$.post("test_post.php", { name: "John Doe", age: "42" }, function(data, textStatus) { alert("Response from server: " + data); });
GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
PUT: Update the addressed member of the collection or create it with the specified ID.
POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
DELETE: Delete the addressed member of the collection.
$.ajax({
url: 'getTwitterFollowers.php',
type: 'GET',
data: 'twitterUsername=jquery4u',
success: function(data) {
//called when successful
$('#ajaxphp-results').html(data);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
jQuery on() method
The on( events [, selector ] [, data ], handler ) method binds a handler to an event (like click) for all current − and future − matched element. It can also bind custom events.
jQuery live() method
The live( type, fn ) method binds a handler to an event (like click) for all current - and future - matched element. It can also bind custom events.
Note: The jQuery live() method deprecated in jQuery 1.7.
jQuery bind() method
The bind( type, [data], fn ) method binds a handler to one or more events (like click) for each matched element. It can also bind custom events.
try this huge collection of...jQuery Interview Questions
ReplyDelete