Categories
jQuery

jQuery — Callbacks

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.

callbacks.disable()

We can call callbacks.disable to disable a callback.

For example, if we have:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.disable();
callbacks.fire("world");

Then we call callbacks.disable to stop the list of callbacks from being called again.

Therefore, we only see:

foo: hello

logged.

callbacks.disabled()

We can use the callbacks.disabled() method to check if callbacks have been disabled.

For example, we can write:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.disable();
console.log(callbacks.disabled());
callbacks.fire("world");

Since we called callbacks.disable , callbacks.disabled should log true .

callbacks.empty()

The callbacks.empty() method removes all callbacks from the list.

For example, we can write:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const bar = function(value) {
  console.log(`bar: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.add(bar);
callbacks.empty();
console.log(callbacks.has(foo));
console.log(callbacks.has(bar));

Since we called callbacks.empty to remove all callbacks, then both console logs should log false since both callbacks have been removed by empty .

callbacks.fire()

The callbacks.fire() method lets us call all callbacks on the list with the given argument.

For example, we can write:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const bar = function(value) {
  console.log(`bar: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.fire("world");
callbacks.add(bar);
callbacks.fire("hello again");

We added the foo callback and called fire with 'hello' and 'world' , so we should get:

foo: hello
foo: world

logged.

Then we added bar to the callbacks list and called fire with 'hello again' .

So we get:

foo: hello again
bar: hello again

logged.

callbacks.fired()

We can check is the callback has been fired at least once with the callbacks.fired() method.

For example, we can write:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.fire("world");
console.log(callbacks.fired());

to log is any callbacks have been called with fired .

Since it’s been called, it should log true .

callbacks.fireWith()

The callbacks.fireWith() method lets us call a callback with the given context and arguments.

For example, if we have:

const log = function(value1, value2) {
  console.log(this, value1, value2);
};

const callbacks = $.Callbacks();
callbacks.add(log);
callbacks.fireWith(window, ["foo", "bar"]);

Then this is window , value1 is foo and value2 is bar .

callbacks.has()

The callbacks.has() method lets us check whether the callbacks list has any callbacks attached.

For example, we can write:

const log = function(value1, value2) {
  console.log(this, value1, value2);
};

const callbacks = $.Callbacks();
callbacks.add(log);
console.log(callbacks.has(log));

The console log should log true since we added it with add .

callbacks.lock()

The callbacks.lock() method locks the callbacks list in its current state.

For example, we can use it by writing:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.lock();
callbacks.fire("world");

We call the callbacks.lock method to prevent any callbacks from being called.

So we only have:

foo: hello

logged.

Conclusion

We can do many things with callbacks with jQuery.

Categories
jQuery

jQuery — Attributes, Before, Blur, and Callbacks

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.

Attribute Starts With Selector [name^=”value”]

This selector let us select elements that have the specified attribute with a value starting exactly with a given string.

For example, if we have:

<input name="newsletter">
<input name="milkman">
<input name="newsboy">

Then we get all the inputs with the name attribute starting with news and setting the value for them by writing:

$("input[name^='news']").val("news here!");

Therefore, the first and last inputs will have the news here input added.

.before()

The .before() method lets us insert content before each element in the set of matched elements.

For example, if we have:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">foo</div>
  <div class="inner">bar</div>
</div>

Then we can add an elements before each div with class inner by writing:

$(".inner").before("<p>Test</p>");

Then we get:

Test

foo

Test

bar

displayed.

.bind()

The .bind() method lets us add a handler to an event for the elements.

For example, if we have the following HTML:

<div id="foo">
  foo
</div>

We can add a click listener to it by writing:

$("#foo").bind("click", function() {
  alert("User clicked on 'foo.'");
});

The first argument is the event name.

The 2nd argument is the callback that’s run when the event is triggered.

.blur()

The .blur() method binds an event handler to the blur JavaScript event.

For example, if we have the following HTML:

<form>
  <input id="target" type="text" value="Field 1">
  <input type="text" value="Field 2">
</form>

Then we can listen to the blur event on the input field with ID target by writing:

$("#target").blur(function() {
  alert("Handler for .blur() called.");
});

We get the element and then pass in the callback to show an alert when we move away from the first input.

:button Selector

The :button select selects all button elements and elements with type set to button .

For example, if we have the following HTML:

<form>
  <fieldset>
    <input type="button" value="Input Button">
    <input type="checkbox">

    <input type="file">
    <input type="submit">
    <input type="text">
    <select>
      <option>Option</option>
    </select>

    <textarea></textarea>
    <button>Button</button>
  </fieldset>
</form>

And the following CSS:

.marked {
  background-color: yellow;
  border: 3px red solid;
}

Then we can get the buttons and add the marked class to them by writing:

const input = $(":button").addClass("marked");
console.log(input.length)

The input with type set to button and the button element will be selected.

callbacks.add()

The callbacks.add method lets us add callbacks to a callback list.

For example, we can write:

const foo = function(value) {
  console.log(`foo: ${value}`);
};

const bar = function(value) {
  console.log(`bar: ${value}`);
};

const callbacks = $.Callbacks();
callbacks.add(foo);
callbacks.fire("hello");
callbacks.add(bar);
callbacks.fire("world");

We call the $.Callbacks method to get a list of callbacks.

Then we call the add method to add the foo and bar methods to add to the callback list.

The callbacks.fire method will call each callback on the list with the given argument.

Therefore, we get:

foo: hello
foo: world
bar: world

from the console log.

Conclusion

We can select items by attribute name and value.

Also, we can listen to various events with jQuery methods.

We can also add callbacks to a list and call them all later.

Categories
jQuery

jQuery — Attributes

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.

.attr()

The .attr() method lets us get or set an attribute for every matched element.

For example, if we have:

<p>Once there was a <em title="huge, gigantic">large</em> cat</p>
<div></div>

Then we can get the title attribute from the em element and put that in the div by writing:

const title = $("em").attr("title");
$("div").text(title);

We can also use it to set the title attribute:

const title = $("em").attr("title", "big");

Attribute Contains Prefix Selector [name|=”value”]

We can get elements by the attribute and name and value. | will get the value equal to the given string or the string followed by a hyphen.

For example, if we have:

<a href="example.html" hreflang="en">Some text</a>

Then we can get this element by writing:

$("a[hreflang|='en']").css("border", "3px dotted green");

hreflang is the attribute name and 'en' is the value.

Attribute Contains Selector [name*=”value”]

This selector selects elements that have specified attribute with a value having a given substring.

For example, if we have the following HTML:

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

Then we get all the inputs with the name attribute having the man substring as the value by writing:

$("input[name*='man']").val("has man");

Now the value of the first 3 input boxes are 'has man' .

Attribute Contains Word Selector [name~=”value”]

We can get the elements that have a specified attribute with a value containing the given word, delimited by spaces.

For example, if we have:

<input name="man-news">
<input name="milk man">
<input name="letterman2">
<input name="newmilk">

Then we can write:

$("input[name~='man']").val("has man");

to get the inputs with the name attribute with the word man in it separated by a space.

Only the 2nd input meets that condition, so has man will be in that input.

Attribute Ends With Selector [name$=”value”]

We can get elements that have the specified attribute with a value ending with the given string.

For example, if we have the following HTML:

<input name="newsletter">
<input name="milkman">
<input name="jobletter">

Then we use this selector by writing:

$("input[name$='letter']").val("a letter");

We get all the inputs with the name attribute with values ending with letter .

Then the first 2 inputs are filled with a letter by calling val .

Attribute Equals Selector [name=”value”]

We can get the elements with the attribute equal to a value with this selector.

For example, if we have the following HTML:

<div>
  <label>
    <input type="radio" name="newsletter" value="Hot Fuzz">
    <span>name?</span>
  </label>
</div>
<div>
  <label>
    <input type="radio" name="newsletter" value="Cold Fusion">
    <span>value?</span>
  </label>
</div>
<div>
  <label>
    <input type="radio" name="newsletter" value="Evil Plans">
    <span>value?</span>
  </label>
</div>

We get the span with the value set to Hot Fuzz and populate the name by text content by writing:

$("input[value='Hot Fuzz']").next().text("Hot Fuzz");

Now the first radio button should have the text Hot Fuzz beside it.

Attribute Not Equal Selector [name!=”value”]

We can use this selector to select an attribute that doesn’t equal to the given value.

For example, if we have the following HTML:

<div>
  <label>
    <input type="radio" name="newsletter" value="Hot Fuzz">
    <span>name?</span>
  </label>
</div>
<div>
  <input type="radio" value="Cold Fusion">
  <span>no name</span>
</div>
<div>
  <label>
    <input type="radio" name="newsletter" value="Evil Plans">
    <span>value?</span>
  </label>
</div>

Then we can get the radio button that doesn’t have name attribute set to newsletter and add text to the span beside it by writing:

$("input[name!='newsletter']").next().append("<b>; not newsletter</b>");

Now the second radio button has:

no name**; not newsletter**

beside the radio button.

Conclusion

We can get and set attributes with the attr method.

Also we can select elements given their attributes with various selectors.

Categories
jQuery

jQuery — Ajax, Animation, and Append

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.

.ajaxStop()

The .ajaxStop() method lets us add a callback that’s called when the Ajax request is done.

For example, we can write:

$(document).ajaxStop(function(event, xhr, settings) {
  console.log(event, xhr, settings)
});

$.ajax({
  url: "https://yesno.wtf/api",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

We passed in a callback with the event , xhr , and settings parameter.

settings has the request data like the URL and request method.

xhr is an object with the request state.

.ajaxSuccess()

The .ajaxSuccess() method lets us add a callback that’s run when an Ajax request completes successfully.

For example, we can write:

$(document).ajaxSuccess(function(event, xhr, settings) {
  console.log(event, xhr, settings)
});

$.ajax({
  url: "https://yesno.wtf/api",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

We have a callback with the same parameters as the other Ajax methods.

All Selector

We can get all elements within another element with the * selector.

For example, if we have:

<div id="test">
  <div>DIV</div>
  <span>SPAN</span>
  <p>P <button>Button</button></p>
</div>

Then we can get all the elements inside the div with ID test by writing:

$("#test").find("*").css("border", "3px solid red")

Then we call css to add a red border in all the elements.

.animate()

The .animate() method lets us perform custom animation of a set of CSS properties.

For example, if we have the following HTML:

<div id="clickme">
  Click here
</div>
<img id="book" src="https://i.picsum.photos/id/25/300/300.jpg?hmac=hXirsaKumNCLu7iGSrMI_RkAEfXF01DGx6c4wzBUpXs" alt="" width="100" height="123"
  style="position: relative; left: 10px;">

We can add an animation to the when we click on Click here by writing:

$("#clickme").click(function() {
  $("#book").animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});

We get the div with ID clickme , then we call click to listen to clicks on it.

Then we call animate to animate the image by changing the left property.

:animated Selector

We can select the element that’s animated with the :animated selector.

For example, if we have the following HTML:

<button id="run">Run</button>

<div></div>
<div id="mover"></div>
<div></div>

And the following CSS:

div {
   background: yellow;
   border: 1px solid #AAA;
   width: 80px;
   height: 80px;
   margin: 0 5px;
   float: left;
 }

div.colored {
   background: green;
}

Then we can toggle the color of the animate div, which has the ID mover by writing:

$("#run").click(function() {
  $("div:animated").toggleClass("colored");
});

function animate() {
  $("#mover").slideToggle("slow", animate);
}

animate();

When we click Run, the toggleClass method is called to change its color.

.append()

We can use the .append method to add elements after another element.

For example, if we have:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Then we can get the elements with the inner class by writing:

$(".inner").append("<p>Test</p>");

Then both divs will have <p>Test</p> HTML attached to it.

Conclusion

We can listen to Ajax events with various methods.

Also, we can animate items and append elements to other elements.

Categories
jQuery

Getting Started with jQuery

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.

Adding jQuery

We can add jQuery by adding a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

We can also install the jquery package by running:

npm install jquery

with NPM or:

yarn add jquery

Also, we can install it with Bower:

bower install jquery

After installing it, we can start using it.

.add()

The .add() method lets us get a child element from a parent.

For example, if we have:

<p>
  <div>
    foo
  </div>
</p>

Then we call:

$("p").add("div").addClass("widget");

to get the div that’s inside the p element.

Then we call addClass to add a class to the div inside the p element.

.addBack()

The .addBack() method lets us get the child elements from the parent element.

For example, if we have the following HTML:

<div class="after-addback">
  <p>First Paragraph</p>
  <p>Second Paragraph</p>
</div>

and the following CSS:

.background {
  background: yellow;
}

Then we get the p elements in the div .

Then we use addBack to get the div again.

And finally, we call addClass to add the background class.

.addClass()

The .addClass() method lets us add one or more classes to an element.

For example, we can write:

$("p").addClass("myClass yourClass");

to add the myClass and yourClass classes to the p element.

.after()

The .after() method inserts content after each element in the set of matched elements.

For example, if we have the following HTML:

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

Then we get the item with the inner class and add the HTML TO it by writing:

$(".inner").after("<p>Test</p>");

.ajaxComplete()

The .ajaxComplete() lets us add a callback that’s called when the Ajax request is completed.

For example, we can write:

$(document).ajaxComplete(function(event, xhr, settings) {
  console.log(event, xhr, settings)
});

$.ajax({
  url: "https://yesno.wtf/api",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

We called ajaxComplete with the callback that’s called when we make a request with $.ajax .

Then we call $.ajax to make the Ajax request.

settings has the url property with the request URL.

The settings.type property has the request method name.

xhr has the XHR object. The readyState property has the ready state.

.ajaxError()

The .ajaxError() method lets us add a callback that’s called when there’s an error.

For example, we can use it by writing:

$(document).ajaxError(function(event, xhr, settings, thrownError) {
  console.log(event, xhr, settings, thrownError)
});

$.ajax({
  url: "bad-url",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

We have an invalid URL set as the value of the url property.

Then the ajaxError callback will be called.

It has the thrownError parameter which isn’t in the ajaxComplete callback.

.ajaxSend()

The ajaxSend method lets us add a callback that’s called when the request is sent.

For example, we can write:

$(document).ajaxSend(function(event, xhr, settings) {
  console.log(event, xhr, settings)
});

$.ajax({
  url: "https://yesno.wtf/api",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

We have the same callback as the other ajax methods.

And the content is the same.

Conclusion

We can add jQuery and call its methods Ajax methods to listen to HTTP requests.

Also, we can use the add and addBack methods to get elements.