Categories
jQuery

jQuery — Resolve/Reject Deferred 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.

deferred.promise()

The deferred.promise() method returns the deferred object’s promise object.

For example, we can use it by writing:

function asyncEvent() {
  const dfd = jQuery.Deferred();
  setTimeout(function() {
    dfd.resolve("hurray");
  }, Math.floor(400 + Math.random() * 2000));

  setTimeout(function() {
    dfd.reject("error");
  }, Math.floor(400 + Math.random() * 2000));

  setTimeout(function working() {
    if (dfd.state() === "pending") {
      dfd.notify("working... ");
      setTimeout(working, 500);
    }
  }, 1);

  return dfd.promise();
}

(async () => {
  try {
    const res = await $.when(asyncEvent())
    cosole.log(res)
  } catch (err) {
    console.log(err);
  }
})()

We have an asyncEvent function that returns a promise from the deferred object in the last line.

It resolves or rejects randomly.

Then in the async function we invoke the promise returned by the asyncEvent function.

deferred.reject()

The deferred.reject() method rejects a deferred object with an argument and calls any failure callbacks.

For example, we can use it by writing:

const deferred = jQuery.Deferred();
deferred.reject('error');

deferred.rejectWith()

The deferred.rejectWith() method rejects a deferred object with the context object and arguments and calls any failure callbacks.

For example, we can write:

const deferred = jQuery.Deferred();
deferred.rejectWith({
    foo: 'bar'
  }, [1])
  .catch(function(err) {
    console.log(this, err);
  })

We call rejectWith with { foo: ‘bar’ } as the this value and [1] as the arguments array.

Then we can get them all in the catch callback.

this is { foo: ‘bar’ } and err is 1.

deferred.resolve()

We can call deferred.resolve() to resolve a deferred object and call any done callbacks with the given arguments.

For example, we can write:

(async () => {
  try {
    const deferred = jQuery.Deferred();
    const res = await deferred.resolve(1)
    console.log(res);
  } catch (error) {
    console.log(error);
  }
})()

We create the deferred object. Then we call deferred.resolve method with the resolved value.

Then we res has the resolved value since we added await before deferred.resolve .

It works because it returns an object with a then method that takes a callback with the resolved value as the parameter.

deferred.resolveWith()

The deferred.resolveWith() lets us resolve a deferred object and call any done callbacks with a context object and arguments.

For example, we can use it by writing:

const deferred = jQuery.Deferred();
deferred.resolveWith({
    foo: 'bar'
  }, [1])
  .then(function(val) {
    console.log(this, val);
  })

We call resolveWith with the this value and an array of arguments.

Then we call then on the returned object with a callback and get the this and val values.

this is { foo: ‘bar’ } and val is 1.

deferred.state()

The deferred.state() method returns the state of the deferred object.

It can return 'pending' , 'resolved' or 'rejected' .

'pending' means the deferred object isn’t completed.

'resolved' means the deferred object is called with deferred.resolve() or deferred.resolveWith().

'rejected' means the deferred object is in a rejected state. Calling deferred.reject() or deferred.rejectedWith() will make it 'rejected' .

For example, we can use it by writing:

const deferred = jQuery.Deferred();
deferred.resolveWith({
    foo: 'bar'
  }, [1])
  .then(function(val) {
    console.log(deferred.state())
  })

Then the console log should log 'resolved' .

Conclusion

We can do many things with the deferred object.

Categories
jQuery

jQuery - Deferred and 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.

.data()

We can store data within matched elements with the data method.

For example, we can write the following HTML:

<span></span>

Then use data to store and get the data as follows:

$("body").data("foo", 52);
$("span").first().text($("body").data("foo"));

We save the data with key 'foo' and value 52 in the first line.

Then in the 2nd line, we get the data and put it in the span .

.dblclick()

The .dblclick() method binds an event handler to the dblclick event or trigger the event on an element.

For example, if we have the following HTML:

<div id="target">
  Double-click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to double clicks on the div with ID target by writing:

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

We can also trigger a double click on the div with ID target when we click on the div with ID other by writing:

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

$("#other").click(function() {
  $("#target").dblclick();
});

deferred.always()

deferred.always() adds a callback to be called when the deferred object is resolved or rejected.

For example, we can write:

$.get("foo.php").always(function() {
  alert("$.get completed");
});

to call the alert when we make a GET request for foo.php .

deferred.catch()

The deferred.catch method adds a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("foo.php")
  .then(function() {
    alert("$.get succeeded");
  })
  .catch(function() {
    alert("$.get failed!");
  });

or:

(async () => {
  try {
    const res = await $.get("foo.php")
  } catch (error) {
    alert("$.get failed!");
  }
})()

$.get returns a thenable object so it works with async and await .

deferred.done()

The deferred.done() method lets us add a callback that’s called when the deferred object is resolved.

For example, we can write:

$.get("https://jsonplaceholder.typicode.com/todos/1")
  .done(function() {
    alert("$.get succeeded");
  });

to make a GET request https://jsonplaceholder.typicode.com/todos/1 and add run something after that.

deferred.fail()

The deferred.fail() method lets us add a callback that’s called when the deferred object is rejected.

For example, we can write:

$.get("test.php")
  .done(function() {
    alert("$.get succeeded");
  })
  .fail(function() {
    alert("$.get failed!");
  });

to add that.

deferred.pipe()

We can use the deferred.pipe() method to filter and chain deferred objects.

It returns another deferred object.

We can use it by writing:

const defer = $.Deferred(),
  filtered = defer.pipe(function(value) {
    return value * 2;
  });

defer.resolve(5);
filtered.done(function(value) {
  alert(value);
});

We call defer.pipe with a callback that takes the resolved value from the defer object, multipole by it by 2, and return it in the callback.

Then we call defer.resolve(5) to pass 5 as the value of value in the pipe callback.

And we get the finalvalue in the done callback, which is 10.

We can chain deferred by writing:

const url = 'https://jsonplaceholder.typicode.com/posts/1';
const url2 = 'https://jsonplaceholder.typicode.com/posts/2';
const request = $.ajax(url, {
    dataType: "json"
  })
  .pipe(function(data) {
    console.log(data)
    return $.ajax(url2);
  })
  .done(function(data) {
    console.log(data)
  });

We call pipe on the first deferred object returned by $.ajax and then call done to get the data from the 2nd $.ajax call.

Conclusion

We can work with deferred objects with various jQuery methods.

Categories
jQuery

jQuery — Clone Elements, Left and Right Clicks, and CSS

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.

.clone()

The .clone() method creates a deep copy of the set of matched elements.

For example, if we have the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

Then we can get the div with class hello , make a copy of it and append it to the div with class goodbye by writing:

$(".hello").clone().appendTo(".goodbye");

.closest()

The .closest() method gets the closest element with the given selector.

For example, if we have the following HTML:

<ul id="one" class="level-1">
  <li class="item-i">I</li>
  <li id="ii" class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

We get the ul that’s closest to the element with the class item-a by writing:

$("li.item-a")
  .closest("ul")
  .css("background-color", "red");

We get both the ul with class level-2 and the ul with class level-3 and add a red background to them.

:contains() Selector

We can use the :contains selector to match elements with the given text.

For example, if we have:

<div>John Smith</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

Then we get all the divs with text 'John' in it and apply styles to it by writing:

$("div:contains('John')").css("text-decoration", "underline");

We add underline to all the divs with text 'John' in it.

So the 1st and 3rd div will have the underline.

.contents()

The .contents() method gives us the content of the element.

For example, if we have:

<div class="container">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
  do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  <br><br>
  Ut enim ad minim veniam, quis nostrud exercitation ullamco
  laboris nisi ut aliquip ex ea commodo consequat.
  <br><br>
  Duis aute irure dolor in reprehenderit in voluptate velit
  esse cillum dolore eu fugiat nulla pariatur.
</div>

Then we get the text nodes by writing:

const els = $(".container")
  .contents()
  .filter(function() {
    return this.nodeType === 3;
  })
console.log(els);

nodeType with value 3 is the text nodes.

.contextmenu()

We can bind to the contextmenu event with the .contextmenu() method.

For example, if we have the given HTML:

<div id="target">
  Right-click here
</div>

Then we can listen to right-clicks by writing:

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

When we right-click the div, then we see the alert displayed.

.css()

We can also use it to get the value of computed styles with the css method lets us set styles for the select elements.

For example, if we have the following HTML:

<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>

And the following CSS:

div {
   width: 60px;
   height: 60px;
   margin: 5px;
   float: left;
}

Then we can listen to clicks and get the style when we click on the div by wiring:

$("div").click(function() {
  const color = $(this).css("background-color");
  console.log(color)
});

We get the background-color property’s value with this.

Also, we can get multiple styles by writing:

$("div").click(function() {
  const styles = $(this).css([
    "width", "height", "color", "background-color"
  ]);
  console.log(styles)
});

We just pass in an array with the property names.

Conclusion

We can clone elements, listen to left and right clicks, and get styles with jQuery.

Categories
jQuery

jQuery — Child Elements, Queues, and Clicks

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.

Child Selector (“parent > child”)

We can get the child elements with this selector.

For example, if we have the following HTML:

<ul class="topnav">
  <li>Item 1</li>
  <li>Item 2
    <ul>
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

We get the ul with the class topnav ‘s li elements bu writing:

$("ul.topnav > li").css("border", "3px double red");

We call css to add a border to all the matched elements.

.children()

We can get the child elements of a selected element with the children method.

For example, if we have the following HTML:”

<ul class="topnav">
  <li>Item 1</li>
  <li>Item 2
    <ul>
      <li>Nested item 1</li>
      <li>Nested item 2</li>
      <li>Nested item 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

Then we get all the child elements of the ul by writing:

$("ul.topnav").children().css("background-color", "red");

We called css to make the background red.

Class Selector (“.class”)

We can select items with the class selector.

For example, if we have the following HTML:

<div class="notMe">div class="notMe"</div>
<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>

Then we can highlight the elements with the class myClass by writing:

$(".myClass").css("border", "3px solid red");

.clearQueue()

The .clearQueue() method removes from the queue items that haven’t been run.

For example, if we have the following HTML:

<button id="start">Start</button>
<button id="stop">Stop</button>
<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;
}

Then we can add a way to start and stop animation by writing:

$("#start").click(function() {
  const myDiv = $("div");
  myDiv.show("slow");
  myDiv.animate({
    left: "+=200"
  }, 5000);

  myDiv.queue(function() {
    const that = $(this);
    that.addClass("newcolor");
    that.dequeue();
  });

  myDiv.animate({
    left: "-=200"
  }, 1500);
  myDiv.queue(function() {
    const that = $(this);
    that.removeClass("newcolor");
    that.dequeue();
  });
  myDiv.slideUp();
});

$("#stop").click(function() {
  const myDiv = $("div");
  myDiv.clearQueue();
  myDiv.stop();
});

In the click callback for the button with ID start, we call queue with callbacks to add animation to the div.

Then in the click callback for the button with ID stop , we call clearQueue to clear the queue then stop the animation with the stop method.

.click()

The click method lets us add an event handler for the click event or trigger the event on an element.

For example, if we have the following HTML:

<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the click event triggered on the div with ID target by writing:

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

Now when we click it, we’ll see the alert popup.

Also, we can trigger the click event programmatically by writing:

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

$("#other").click(function() {
  $("#target").click();
});

When we click the div with ID other , we trigger the click event on the div with ID target .

Conclusion

We can get child elements, clear the queue, and trigger or listen to clicks with jQuery.

Categories
jQuery

jQuery — Callbacks and Checkboxes

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.locked()

We can use the callbacks.locked() method to check if the callbacks list has been locked.

For example, if we write:

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

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

Then the last console log should be true since we called lock to lock the callbacks list.

callbacks.remove()

We can remove a callback with the callback.remove method.

For example, we can write:

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

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

We called remove on foo to remove foo from the callbacks list.

Therefore, then 2nd fire callback won’t call foo .

.change()

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

It can also be used to trigger an the change event on an element.

For example, if we have the following HTML:

<form>
  <input class="target" type="text" value="Field 1">
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>

Then we can listen to the change event triggered on the elements with the class target by writing:

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

We can also trigger the change ebent on the element.

For example, if we have the following HTML:

<form>
  <input class="target" type="text" value="Field 1">
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  click me
</div>

Then we can add a click listen to the div with ID other .

When we click the div, we can trigger by change event on all the elements with class target by writing:

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

$("#other").click(function() {
  $(".target").change();
});

Now when we click the click me button, we’ll see the alert pop up for each element with class target .

:checkbox Selector

The :checkbox selector lets us select all elements with type checkbox .

For example, if we have the following HTML:

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

  <input type="checkbox">
  <input type="file">
  <input type="hidden">
   <input type="password">
  <input type="radio">

  <input type="reset">
  <input type="submit">
  <input type="text">

  <select>
    <option>Option</option>
  </select>

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

Then we can highlight all the checkboxes by writing:

$("form input:checkbox")
  .wrap("<span></span>")
  .parent()
  .css({
    background: "yellow",
    border: "3px red solid"
  });

We get the checkboxes with the :checkbox selector and set the background and border of all the selected elements.

:checked Selector

We can get all the checked checkboxes with the :checked selector.

For example, if we have the following HTML:

<form>
  <p>
    <input type="checkbox" name="newsletter" value="Hourly" checked="checked">

    <input type="checkbox" name="newsletter" value="Daily">
    <input type="checkbox" name="newsletter" value="Weekly">

    <input type="checkbox" name="newsletter" value="Monthly" checked>
    <input type="checkbox" name="newsletter" value="Yearly">
  </p>
</form>

Then we can highlight the checked checkboxes by writing:

$("input:checked")
  .wrap("<span></span>")
  .parent()
  .css({
    background: "yellow",
    border: "3px red solid"
  });

Conclusion

We can lock the callbacks list and select checkboxes with jQuery.