Categories
jQuery

jQuery — Queues and Serialized Data

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

jQuery.merge()

The jQuery.merge() method merges the contents of 2 arrays together into the first array.

For example, we can use it by writing:

const arr = $.merge([0, 1, 2], [2, 3, 4])
console.log(arr);

Then arr is:

[0, 1, 2, 2, 3, 4]

jQuery.noConflict()

The jQuery.noConflict() method relinquishes jQuery’s control of the $ variables.

We can use it by writing:

jQuery.noConflict();
jQuery( "div p" ).hide();

We call noConflict .

Then we can invoke jQuery with jQuery instead of $ .

jQuery.noop()

The jQuery.noop() method returns an empty function.

jQuery.param()

The jQuery.param() method converts an object’s key-value pairs into a query string.

For example, we can write:

const params = {
  width: 1680,
  height: 1050
};
const str = jQuery.param(params);
console.log(str)

Then str is ‘width=1680&height=1050’ .

jQuery.parseHTML()

The jQuery.parseHTML() method lets us parse a string into an array of DOM nodes.

For example, if we have:

<div id="log">
  <h3>Content:</h3>
</div>

Then we can append the parsed HTML into the div with ID log by writing:

const str = "hello, <b>my name is</b> jQuery.";
const html = $.parseHTML(str);
$("#log").append(html);

We parse the HTML string with $.parseHTML and then call append to append the item.

jQuery.parseJSON()

We can parse JSON string into an object with the jQuery.parseJSON() the method.

For example, if we have:

const obj = jQuery.parseJSON('{ "name": "John" }');
console.log(obj.name === "John");

Then we parse the string into the obj object.

The obj.name value is 'John' .

So the console log logs true .

jQuery.parseXML()

The jQuery.parseXML() method lets us parse XML into an object.

For example, we can use it by writing:

const xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
  xmlDoc = $.parseXML(xml),
  $xml = $(xmlDoc),
  title = $xml.find("title");
console.log(title.text())

We call parseXML with the XML string.

Then we put that into the $ function so that we can call find to find the element we want.

Then we can get the text of the matched element with the text method.

jQuery.post()

The jQuery.post() method lets us make a POST request to a given URL.

For example, we can write:

const jqxhr = $.post("https://jsonplaceholder.typicode.com/posts", {
    title: "title",
    body: "body"
  }, function() {
    console.log("success");
  }, "json")
  .done(function() {
    console.log("second success");
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("finished");
  });

jqxhr.always(function() {
  console.log("second finished");
});

to make a POST request.

The 2nd argument is the form data keys and values we want to send with the request.

The done callback is called when the request is successful.

The fail callback is called when the request failed.

always callback is called when the request is finished regardless of the result.

jQuery.queue()

The jQuery.queue() method show or manipulate the queue of functions to be run on the matched element.

For example, if we have the following HTML:

<div></div>

and CSS:

div {
  margin: 3px;
  width: 40px;
  height: 40px;
  position: absolute;
  left: 0px;
  top: 30px;
  background: green;
  display: none;
}

div.newcolor {
  background: blue;
}

span {
  color: red;
}

Then we can animate the div by writing:

$("div")
  .show("slow")
  .animate({
    left: "+=200"
  }, 2000)
  .slideToggle(1000)
  .slideToggle("fast")
  .animate({
    left: "-=200"
  }, 1500)
  .hide("slow")
  .show(1200)

console.log(jQuery.queue($("div")[0], "fx"))

We get the div and use that as the argument of jQuery.queue to check the items that are queued.

Conclusion

We can parse JSON and XML and queue actions with jQuery.

Categories
jQuery

jQuery — Array and Object Operations

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

jQuery.globalEval()

We can use the jQuery.globalEval() method to run some JavaScript code globally.

For example, we can write:

jQuery.globalEval("let newVar = true;");

to run some code.

jQuery.grep()

The jQuery.grep() method finds the element of an array that satisfies the filter function.

For example, we can write:

const arr = [1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1];
const filteredArr = jQuery.grep(arr, function(n, i) {
  return (n !== 5 && i > 4);
});

console.log(filteredArr)

Then we returned an array that has the result that satisfies the condition in the callback we passed into grep .

n has the array entry. i has its index.

jQuery.hasData()

The jQuery.hasData() method lets us check if a piece of data is saved into an element.

For example, if we have:

<p> </p>

Then we can use it by writing:

const p = jQuery("p")[0];
console.log(jQuery.hasData(p));
$.data(p, "testing", 123);
console.log(jQuery.hasData(p))

We call hasData on the p element to check if there are any data saved into it.

So the first console log should log false and the 2nd one should log true .

jQuery.inArray()

The jQuery.inArray() method lets us check if an element is in the array.

It returns the index of it if it’s found and -1 otherwise.

For example, we can write:

console.log($.inArray(5 + 5, ["8", "9", "10", 10 + ""]));

to check if 10 is in the array.

It should return -1 since it’s not in the array.

jQuery.isEmptyObject()

We can check if an element is an empty object with the jQuery.isEmptyObject() .

For example, if we have:

console.log(jQuery.isEmptyObject({}));

This should log true since we passed in an empty object into the method.

jQuery.isPlainObject()

The jQuery.isPlainObject() method lets us check if a JavaScript object is a plain object.

A plain object is an object literal.

For example, if we have:

console.log(jQuery.isPlainObject({}))
console.log(jQuery.isPlainObject("test"))

Then the first console log logs true and the 2nd one logs false .

jQuery.isXMLDoc()

We can check if a document object is an XML document with thejQuery.isXMLDoc() method.

For example, we can write:

console.log(jQuery.isXMLDoc(document))

Then the console log logs false .

jQuery.makeArray()

We can use the jQuery.makeArray() method to convert an element list to an array.

For example, if we have:

<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>

Then we can write:

const elems = document.getElementsByTagName("div");
const arr = jQuery.makeArray(elems);
console.log(arr)

We get the divs with getElementsByTagName .

Then we call jQuery.makeArray to convert the element list to an array.

jQuery.map()

The jQuery.map() method translates all items in an array or object to a new array of items.

For example, we can write:

const fakeArray = {
  "length": 2,
  0: "foo",
  1: "bar"
};
const realArray = $.makeArray(fakeArray)
const mapped = $.map(realArray, function(val, i) {
  return val + val;
});

console.log(mapped);

fakeArray is an object with numeric keys and a length property.

We call $.makeArray to convert that into a real array.

Then we call $.map to map the array entries into new values.

So mapped is [“foofoo”, “barbar”] .

Conclusion

We can do various objects and array operations with jQuery methods.

Categories
jQuery

jQuery — Iteration, Requests, and Objects

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

jQuery.each()

We can iterate over objects, arrays, and array-like objects with the length property with the each method.

For example, if we have:

$.each([52, 97], function(index, value) {
  console.log(index, value);
});

Then we log the index and value for each entry in the array.

jQuery.escapeSelector()

We can escape any character that has special meaning in a CSS selector with the escapeSelector method.

For example, we can write:

console.log($.escapeSelector( "#target" ))

to return the escaped string.

So we see:

'#target'

logged.

jQuery.extend()

The jQuery.extend() method lets us merge 2 or more objects together into the first object.

For example, we can write:

const object1 = {
  apple: 0,
  banana: {
    weight: 52,
    price: 100
  },
  cherry: 97
};
const object2 = {
  banana: {
    price: 200
  },
  durian: 100
};

$.extend(object1, object2);
console.log(object1)

Then we get:

{
  "apple": 0,
  "banana": {
    "price": 200
  },
  "cherry": 97,
  "durian": 100
}

as the value of object1 .

jQuery.fn.extend()

The jQuery.fn.extend() method lets us merge the content of an object into the jQuery prototype to add new jQuery instance methods.

For instance, if we have:

<label><input type="checkbox" name="foo"> Foo</label>
<label><input type="checkbox" name="bar"> Bar</label>

Then we can add the check and uncheck instance methods by writing:

jQuery.fn.extend({
  check() {
    return this.each(function() {
      this.checked = true;
    });
  },
  uncheck() {
    return this.each(function() {
      this.checked = false;
    });
  }
});

$("input[type='checkbox']").check();

They set the checked property to true and false respectively.

Now we can call it as we do in the last line to get check and uncheck the checkboxes.

jQuery.fx.off

The jQuery.fx.off method globally disables all animations.

For example, if we have the following HTML:

<input type="button" value="Run">
<button>Toggle fx</button>
<div></div>

and CSS:

div {
  width: 50px;
  height: 30px;
  margin: 5px;
  float: left;
  background: green;
}

Then we can toggle the animation effect for the div bu writing:

const toggleFx = function() {
  $.fx.off = !$.fx.off;
};
toggleFx();
$("button").click(toggleFx);
$("input").click(function() {
  $("div").toggle("slow");
});

The toggleFx method toggles the animation.

Then we run the toggle method when we click the button.

jQuery.get()

The jQuery.get() method lets us make a GET request.

For example, we can write:

$.get("https://jsonplaceholder.typicode.com/posts/1", function(data) {
  console.log(data)
});

to make a GET request with the given URL.

The callback’s data parameter has the data from the response.

jQuery.getJSON()

The jQuery.getJSON() method lets us make a request and get the JHSON response from it.

For example, we can write:

$.getJSON("https://jsonplaceholder.typicode.com/posts/1", function(data) {
  console.log(data)
});

to make a request as we do with the get method.

jQuery.getScript()

The jQuery.getScript() method lets us get a script from a server/

For example, we can use it by writing:

$.getScript("https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", function(data, textStatus, jqxhr) {
  console.log(data);
  console.log(textStatus);
  console.log(jqxhr.status);
});

Then we get the textStatus and jqxhr.status to get the request status.

data has the response data.

Conclusion

We can call various jQuery static methods to make HTTP requests or add instance methods to jQuery.

Also, we can manipulate objects with jQuery static methods.

Categories
jQuery

jQuery — Callbacks, CSS Hooks, and Queues

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

jQuery.Callbacks()

The jQuery.Callbacks() method lets us create a callback list to manage callbacks.

For example, we can write:

const fn1 = (val) => console.log('fn1', val);
const fn2 = (val) => console.log('fn2', val);
const callbacks = $.Callbacks();
callbacks.add(fn1);
callbacks.fire("foo!");
callbacks.add(fn2);
callbacks.fire("bar!");

We call $.Callbacks() to returns the callbacks list object.

Then we call add to add the callback functions.

And we call fire to call the callbacks with the given argument.

So, we’ll get:

fn1 foo!
fn1 bar!
fn2 bar!

logged in the console.

jQuery.contains()

The jQuery.contains() method lets us check to see if a DOM element is a descendant of another DOM element.

For example, we can write:

console.log($.contains(document.documentElement, document.body));

to check if the body element is in the document element.

This should return true since body is in document.

jQuery.cssHooks

The jQuery.cssHooks lets us hook directly into jQuery to override how CSS properties are retrieved or set.

We can also change how CSS properties are normalized, property naming, or create custom properties.

For example, if we have:

<div id='element'>
  foo
</div>
<div id='another'>
  bar
</div>

Then we can specify how the border-radius CSS property is get and set by writing:

const borderRadius = "borderRadius";

$.cssHooks.borderRadius = {
  get(elem, computed, extra) {
    return $.css(elem, borderRadius);
  },
  set(elem, value) {
    elem.style[borderRadius] = value;
  }
};

$("#element").css("borderRadius", "10px");
$("#another").css("border-radius", "20px");

jQuery.cssNumber

The jQuery.cssNumber object has all the CSS properties that may be used without a unit.

For example, we can set the borderRadius CSS property to be used without a unit by writing:

jQuery.cssNumber.borderRadius = true;

The default object has the following properties set to true :

  • zIndex
  • fontWeight
  • opacity
  • zoom
  • lineHeight
  • widows
  • orphans
  • fillOpacity
  • columnCount
  • order
  • flexGrow
  • flexShrink

jQuery.data()

We can save arbitrary data associated with the specified element and returned what value was set with the jQuery.data() method.

For example, if we have:

<div>
  The values stored were
  <span></span>
  and
  <span></span>
</div>

Then we can save data into the div and get it by writing:

const div = $("div")[0];
jQuery.data(div, "test", {
  first: 16,
  last: "pizza!"
});
$("span").first().text(jQuery.data(div, "test").first);
$("span").last().text(jQuery.data(div, "test").last);

We call jQuery.data with the div to save the data.

The first argument is the element to save the data.

The 2nd argument is the key to get the data.

And the last argument is the object we’re saving.

Then we get the data in the last 2 lines and set them as the text content of the span.

jQuery.Deferred()

The jQuery.Deferred() method is a factory function that returns a chainable utility object with methods to register callbacks, invoke callbacks, and relay success or failure states of any sync or async operation.

jQuery.dequeue()

The jQuery.dequeue() method lets us run the next function on the queue for the matched element.

For example, if we have the following HTML:

<button>Start</button>
<div></div>

and the following CSS:

div {
  margin: 3px;
  width: 50px;
  position: absolute;
  height: 50px;
  left: 10px;
  top: 30px;
  background-color: yellow;
}

div.red {
  background-color: red;
}

Then when we click on the Start button, we animate the div by writing

$("button").click(function() {
  $("div")
    .animate({
      left: '+=200px'
    }, 2000)
    .animate({
      top: '0px'
    }, 600)
    .queue(function() {
      $(this).toggleClass("red");
      $.dequeue(this);
    })
    .animate({
      left: '10px',
      top: '30px'
    }, 700);
});

We call $.dequeue to call invoke the animation in the animate method.

Conclusion

We can add and run callbacks, change how CSS properties, and more with jQuery.

Categories
jQuery

jQuery — Check Elements and Ajax

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.is()

The is method lets us check the current matched set of elements against a selector, element, or jQuery object.

It returns true if at least one of thee elements matches the given elements.

For example, if we have:

<ul>
  <li>list <strong>item 1</strong></li>
  <li><span>list item 2</span></li>
  <li>list item 3</li>
</ul>

Then we can check if the element we currently clicked on is an li and add a red background to it by writing:

$("ul").click(function(event) {
  const target = $(event.target);
  if (target.is("li")) {
    target.css("background-color", "red");
  }
});

jQuery()

The jQuery() function takes a string with a CSS selector to match a set of elements.

For example, if we have the following HTML:

<div class='foo'>
  <span>foo</span>
</div>
<div>
  bar
</div>

and CSS:

.bar {
  background: green
}

We can add the bar class to a span inside the div with class foo by writing:

$("div.foo").click(function() {
  $("span", this).addClass("bar");
});

.jquery

The .jquery property lets us get a string containing the jQuery version number.

So we can write:

console.log($.fn.jquery)

to get that.

jQuery.ajax()

We can make an Ajax request with the jQuery.ajax() method.

For example, we can make a GET request by writing:

const jqxhr = $.ajax("https://jsonplaceholder.typicode.com/posts/1")
  .done(function() {
    alert("success");
  })
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("complete");
  });

jqxhr.always(function() {
  alert("second complete");
});

We call done with a callback to run something after the request is successful.

The fail callback is run when the request fails.

The always callback is run whenever the request is done regardless of outcome.

jqxhr.always ‘s callback is run whenever the request is done regardless of outcome.

jQuery.ajaxPrefilter()

The jQuery.ajaxPrefilter() method handles custom Ajax options or modifies existing options before each request is sent and before they’re processed by $.ajax() .

For example, we can write:

const currentRequests = {};

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  if (options.abortOnRetry) {
    if (currentRequests[options.url]) {
      currentRequests[options.url].abort();
    }
    currentRequests[options.url] = jqXHR;
  }
});

$.ajax("https://jsonplaceholder.typicode.com/posts/1")
  .done(function() {
    alert("success");
  })

to check if the abortOnRetry option is enabled and call abort if the request URL is in the currentRequests object.

This way, it won’t retry after it’s already been tried.

jQuery.ajaxSetup()

The jQuery.ajaxSetup() method lets us add set default values for future Ajax requests.

But its use isn’t recommended.

For example, we can write:

$.ajaxSetup({
  url: "https://jsonplaceholder.typicode.com/posts/1"
});

$.ajax()
  .done(function() {
    alert("success");
  })

Then the default URL to make the request to is ”https://jsonplaceholder.typicode.com/posts/1" .

jQuery.ajaxTransport()

We call the jQuery.ajaxTransport() method to create an object that handles the transmission of Ajax data.

For example, we can write:

jQuery.ajaxSetup({
  accepts: {
    script: "application/json"
  },
  contents: {
    script: /json/
  },
  converters: {
    "text script": jQuery.globalEval
  }
});

$.ajax("https://jsonplaceholder.typicode.com/posts/1")
  .done(function() {
    alert("success");
  })

to add the application/json header to our request.

Conclusion

We can check element type with the is method.

Also, we can call various method to set up our Ajax requests.