Categories
jQuery Tips

jQuery Tips — Slim Package, each and reverse, Copy to Clipboard

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

Using jQuery .each() to Iterate Backwards

To call each to iterate through an array backward, we can use the reverse method to reverse the items.

For instance, we can write:

$($("li").get().reverse()).each(function() {
  /* ... */
});

We get all the li elements, convert the Node list to an array with get .

Then we call reverse to reverse the items.

Now we can call each to iterate through each item in reverse.

We can also create our own reverse plugin to reverse the items.

For example, we can write:

$.fn.reverse = [].reverse;
$("li").reverse().each(function (i) {
    $(this).text(`item-${i}`);
});

We created the reverse jQuery plugin with by getting the reverse method of the array and returning it.

Then we can call reverse with our jQuery object.

Then that returns an array and we can call each on it.

Use the Same Click Event for Multiple Elements with jQuery

We can add the same click handler to multiple elements by using the on method.

For instance, we can write:

$('.foo, .bar').on('click', onClick);

where onClick is an event handler function.

We listen to the click event on all elements with class foo and bar .

We can also use the on method to listen to multiple events with multiple elements.

For example, we can write:

$(document).on("click touchend", ".foo, .bar, .baz", function () {
  //...
});

We listen to the click and touchend events with all elements with the classes foo , bar , and baz .

The function is the event handlers.

We call on on the document object so that we can do event delegation with it.

Differences Between Normal and Slim Package of jQuery

The slim jQuery package has several features removed from the normal jQuery package.

jQuery.fn.extend is removed fo we can’t create our own instance methods with the jQuery constructor.

jQuery.fn.load is also removed so we can’t load data from the ether and place the returned HTML into a given element.

jQuery.each is also removed, so we can’t iterate over array items with it.

jQuery.expr.filters.animated is removed so that we can’t use it for animations.

Ajax methods like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, and jQuery.ajaxTransport are also gone.

XML parsing methods like jQuery.parseXML is also removed.

jQuery.easing , jQuery.animation and jQuery.speed aren’t included in the jQuery slim package.

These are animation effect packages that we may not need.

If we don’t use these methods, then we can use the jQuery slim package instead of the normal one.

jQuery Set Cursor Position in Text Area

We can set the cursor position in the text area by using the setSelectionRange or the createTextRange method.

For instance, we can write:

const setSelectionRange = (input, selectionStart, selectionEnd) => {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    const range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

We check if the setSelectionRange method and use that if it exists.

We call focus on the input and then call setSelectionRange to set the selection from by the start and end position.

With the createTextRange method, we can do the same thing.

It’s more complex that setSelectionRange .

We have moveEnd and moveStart to move the selection cursor to the position that we want.

And then we call select to make the selection.

Copy to Clipboard Using jQuery

We can create a function to copy to clipboard using jQuery.

The function would create an input, put the text in it, and then select the text.

Then we call execCommand with the argument 'copy' to copy the selection to the clipboard.

And then we remove the element that we created.

For instance, we can write:

const copyToClipboard = (element) => {
  const $tempInput = $("<input>");
  $("body").append($tempInput);
  $tempInput.val($(element).text()).select();
  document.execCommand("copy");
  $tempInput.remove();
}

We created an input element, attached it to the body.

And then put whatever element’s text into the element as its value.

Then we call select in it to select all the text.

And then we call execCommand on it.

Once that’s done we remove the element by calling remove .

Conclusion

We can copy text to the clipboard by putting it in an input and then send the 'copy' command on it.

With jQuery, we can attach multiple events to multiple elements.

And we can create our own reverse jQuery plugin to reverse the item we iterate through.

Categories
jQuery Tips

jQuery Tips — Checkboxes, Loading Messages, Getting Elements

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

jQuery Selectors on Custom Data Attributes

We can select custom data attributes by passing the data attribute name and value into the CSS selector.

For instance, we can write:

$("ul[data-group='fruits'] li[data-choice='apple']")

The code gets the ul with the data-group attribute set to fruits and the li inside it with the data-choice attribute set to apple .

We can also get elements with a data attribute not equal to something.

For instance, we can write:

$("ul[data-group='`fruits`'] li:not([data-choice='`apple`'])")

This gets the ul element with data-group attribute set to fruits .

And data-choice attribute is not set to apple as indicated by the not selector.

jQuery UI has the custom :data selector.

Check State Changed Even with jQuery Checkbox

To watch for state changes of a checkbox, we can call the change method.

For instance, we can write:

$("#checkbox").change(function() {
  if(this.checked) {
    //...
  }
});

We get the checkbox with ID checkbox and call change on it to listen for changes for the checkbox.

In the callback we pass in, we use this.checked to get the checked value of the checkbox.

Alternatively, we can use the on method to listen for the change event.

For example, we can write:

$(document).on('change', '#checkbox', function() {
  if (this.checked) {
    //...
  }
});

We call the on method to listen to events.

We call it on document so that we can do event delegation.

'change' means we’re listening to the change event.

'#checkbox' is the selector for the checkbox element that we’re listening to.

The 3rd argument is the callback.

document.getElementById vs jQuery $()

We can achieve the same effect as document.getElementById with the $ function.

To do that, we can write:

const fooEl = $('#foo')[0];

The [0] is what’s needed to get the DOM object of the element with ID foo .

That is the same as:

document.getElementById('foo');

Removing Multiple Classes with jQuery

To remove multiple classes with jQuery, we can call removeClass to remove multiple classes.

Each class should be separated by a space in a string.

For instance, we can write:

$("#foo").removeClass("class1 class2");

Then we cal remove the class1 and class2 classes from the element with ID foo with the removeClass method.

Escaping HTML Strings with jQuery

To escape HTML strings, we can pass it through the text method and then call the html method to return text that’s escaped with HTML entities.

For instance, if we have:

$('<div/>').text('peter, paul & mary').html();

We get:

"peter, paul &amp; mary"

returned.

Get Class Name of an Element

To get the class names of an element, we can do that in various way,

One way is to use the attr method with 'class' as the argument.

For instance, we can write:

const className = $('#foo').attr('class');

The get the class attribute of the element with ID foo as a string.

In event handlers for jQuery objects, we can use the className property of this to get the element.

For example, we can write:

$('#foo').click(function() {
  console.log(this.className);
});

We get the className property in the click handler for the element with ID foo .

The hasClass method lets us check if a class is added to an element.

For instance, we can write:

$('#foo').hasClass('class');

We can check if the class class name is added to the element with ID foo .

Check if Object is a jQuery Object

We can check if an object is a jQuery object using the instanceof operator.

For example, we can write:

if (obj instanceof jQuery){
  console.log('obj is a jQuery object');
}

We just check of obj is an instance of jQuery to check that.

Show a “ Loading…” Message Using jQuery

To make this easy, we just add an element with a loading message and show and hide it depending on what we’re doing.

For instance, for an ajax request, we can create a loading message by writing:

<div id="loading">
  <p>loading...</p>
</div>

Then we can write:

$(document)
  .ajaxStart(() => {
     $('#loading').show();
  }).ajaxStop(() => {
     $('#loading').hide();
  });

to toggle a message on and off.

We toggle the loading message on when an ajax request starts with ajaxStart ‘s callback.

And we do hide the loading message when the ajax request is done with the ajaxStop callback.

Conclusion

We can check if a checkbox if checked by listening to various events.

And we can show or hide a loading message with jQuery.

Strings can also be escaped with HTML entities.

Class names can be retrieved in various ways.

Categories
jQuery Tips

jQuery Tips — Class Names, List Elements, and Debounce

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

Get Class List for Element with jQuery

To get the class list for an element with jQuery, we can get the class attribute of an element and the split the class list string by any whitespace.

To do that, we can write:

$(element).attr("class").split(/s+/);

We get the element and get the class attribute with attr .

Then we call split with /s+/ which matches any whitespace.

To make our lives easier, we can use the classList property.

We can do that by getting the DOM element.

For instance, we can write:

$(element)[0].classList

We just get the classList property to get the list of classes.

The DOM element is accessed by the index.

Delay the Keyup Handler Until the User Stops Typing

We can make our own function that takes a callback that calls setTimeout with the callback that we pass in as the callback to delay running the callback.

For instance,e we can write:

const delay = (fn, ms) => {
  let timer = 0
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(fn.bind(this, ...args), ms || 0)
  }
}

We created the delay function, which takes the callback that we want to run, which is fn .

ms is the delay that we want to delay duration that we can to have before running the fn callback.

We have the timer that returns a function that takes some arguments that we can pass into the fn callback.

We also set the value of this to the element that we call keyup on by passing this as the first argument of bind .

In the function we return, we call clearTimeout on the timer if there is one set.

We’ve to return a traditional function so that we get the right value of this , which is the element we’re listening to the keyup event for.

And then we call setTimeout with fn with the value of this we described and the arguments we pass in.

To use it, we can write:

<input id="input" type="text" placeholder="enter your name"/>
</label>

Then we can write:

$('#input').keyup(delay(function (e) {
  console.log(this.value);
}, 1500));

We get the input with ID input with jQuery.

Then we call keyup to with our delay function with the keyup event listener passed into it.

Then we can log the value of the input with this.value .

This way, we see the value that we typed in.

The delay is set to 1500 ms or 1.5 seconds.

If we don’t want to make our own function, we can also use the Underscore or Lodash’s debounce method.

For instance, we can write:

const debouncedOnKeyup = _.debounce(function (e) {
  console.log(this.value);
}, 1500);

$('#input').keyup(debouncedOnKeyup);

We call the Underscore or Lodash debounce method to add a delay to our event handler function.

Then we call keyup to run the keyup handler with a delay.

Wait for All Images to Load Before Executing Something with jQuery

To wait for images to load before running something on jQuery, we can wait for the document to ready.

We can also watch the load event of window and run code after it’s emitted.

To wait for the document to be ready, we can write:

$(document).ready(() => {
  //...
});

We call ready on the document jQuery object with a callback.

Also, we can watch the load event by writing:

$(window).on("load", () => {
  //...
});

The callback is run when the load event is triggered on the window object.

Get Selected Element Tag Name with jQuery

We can get the tagName property with the prop method to get the tag name.

For example, we can write:

$("<a>").prop("tagName");

We get the tag name of the a element with the 'tagName' string.

Also, we can make that into a plugin.

For example, we can write:

$.fn.tagName = function() {
  return this.prop("tagName");
};

Then we can write:

$("<a>").tagName();

after the plugin is defined.

Conclusion

We can get the tag name of a jQuery element with the tagName property.

There are various ways to get the class list.

Also, there’re various ways to delay the key up handler.

To make sure that images are loaded in the document, we can watch the window or document events to check if it’s ready.

Categories
jQuery Tips

jQuery Tips — Multiple Ajax Requests, Scrolling, and Search Parts of an Attribute

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

Wildcards in jQuery Selectors

There are a few ways to add wildcards to selectors that we use for getting elements with jQuery.

To get an element that has an ID that starts with the given string, we can write:

$("[id^=foo]")

The ^ means that we look for an element with an ID that starts with foo .

We can use the $ symbol to search for an element with an ID that ends with the given string.

For example, we can write:

$("[id$=foo]")

The $ means that we look for an element with an ID that ends with foo .

We can substitute id with any other attribute.

Also, we can use the asterisk to look for part of an attribute anywhere.

For instance, we can write:

$("[id*=foo]")

* means that we look for foo in ID’s value anywhere.

Check if a User has Scrolled to the Bottom

We can check if a user has scrolled to the bottom, we can call the scroll method with a callback.

In the callback, we can call the scrollTop property to get current vertical position of the scroll bar for the window.

We add that to the height of the window.

Then we sum that up and then compare that against the document’s height.

For instance, we can write:

$(window).scroll(() => {
   if ($(window).scrollTop() + $(window).height() === $(document).height()) {
     console.log("scroll to bottom");
   }
});

We compare the scrolled height with the document’s height to see if the user scrolled to the bottom.

Wait Until All jQuery Ajax Requests are Done

To wait until all jQuery Ajax requests are done, we can call the when method with the jQuery ajax calls as arguments.

This way, we wait for all requests to be done and get all the results.

For instance, we can write:

const ajax1 = () => {
  return $.ajax({
    url: "/foo",
    dataType: "json",
    data,
    //...
  });
}

//...

$.when(ajax1(), ajax2(), ajax3())
  .done((a1, a2, a3) => {
    //...
});

We have 3 Ajax functions ajax1 , ajax2 , and ajax3 .

They all return the promise that we get by calling $.ajax .

We make the promise for each request, then we pass in that result.

Then we call done to get the result for all the promises.

a1 , a2 , and a3 are the result for each promise.

Since $.ajax return promises, we can pass that into Promise.all .

For instance, we can write:

Promise.all([ajax1(), ajax2(), ajax3()])
  .then(([a1, a2, a3]) => {
    //...
  }).catch(() => {
    //...
  })

Promise.all lets us get the results for all the requests just like jQuery’s when .

We pass in an array of promises, which ajax returns.

Then we call then to do something after the promises are done.

The result for each promise is in an array in the first parameter of the then callback.

With the async and await syntax, we can write:

const makeRequests = async () => {
  try {
    const results = await Promise.all([ajax1(), ajax2(), ajax3()]);
  } catch(ex) {
    console.log(ex);
  }
}

We just rewrite the code with a shorter syntax, but the code does the same thing as the then .

results has an array of results from all the promises.

Select <a> Element with href that Ends with Some String

We can get an <a> element that ends with a given string with the $= operator.

For instance, we can write:

$('a[href$="foo"]')

This will get the href attribute that ends with the foo .

In addition to $= , there are many operators to let us check for other parts of the string.

= is exactly equal.

!= is not equal.

^= means starts with.

$= is ends with.

*= means contains.

~= means the match contains a word.

|= means it starts with the given prefix. A prefix is something like prefix- .

Conclusion

There are many operators to let us match various parts of an attribute value.

Also, we can check if the user scrolled to the bottom by comparing the height.

Wildcards can be included with CSS selectors used with jQuery.

There are many ways to run code after all jQuery Ajax requests are done.

Categories
jQuery Tips

jQuery Tips — Attribute Check, Break out of Each, and Form Submission

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

Check to See if There is an Attribute on an Element

We can check to see if there’s an attribute on an element by using the attr method to get the attribute with the given name.

For instance, we can write:

const attr = $(this).attr('name');

if (typeof attr !== 'undefined' && attr !== false) {
  // ...
}

We check if attr isn’t undefined and that it’s not false in the if statement.

Plain JavaScript also has the hasAttribute method.

For example, we can write:

this.hasAttribute("name")

where this is the DOM element object.

Preloading Images with jQuery

To preload images with jQuery, we can create our image element and then we cat set the src properties to the URL for the image.

For instance, we can write:

const arrayOfImages = [
  'http://placekitten.com/200/200',
  'http://placekitten.com/201/201',
  'http://placekitten.com/199/199'
];

$(arrayOfImages).forEach((a) => {
  $('<img/>')[0].src = a;
});

We create an img element on the fly and set the src property to the URL that we want.

Also, we can use the Image constructor to create the image element.

For example, we can write:

const arrayOfImages = [
  'http://placekitten.com/200/200',
  'http://placekitten.com/201/201',
  'http://placekitten.com/199/199'
];
$(arrayOfImages).each((a) => {
  (new Image()).src = a;
});

The a parameter in the callback is the URL.

jQuery Ajax POST Request with PHP

We can use the ajax method with to thw PHP script that we want to make the request to.

For instance, we can write:

const data = $('form').serialize();

$.ajax({
  url: "test.php",
  type: "post",
  data,
  success: (response) => {
     //...
  },
  error: (jqXHR, textStatus, errorThrown) => {
     console.log(textStatus, errorThrown);
  }
});

We make a POST request to test.php by first serializing the input values with the serialize method so that we can send the values.

We can then call the ajax method with an object that has the URL to make the request to.

type is the type of request.

data has the data.

success has the request success handler.

error has the error handler, which is invoked when a network error occurs.

If we want to submit a form on submit, we can call the submit method on the form element.

And in the callback for submit , we can make the Ajax request the same way.

For instance, we can write:

$("form").submit(function(event) {
  event.preventDefault();
  const data = $(this).serialize();

  const ajaxRequest = $.ajax({
    url: "test.php",
    type: "post",
    data
  });

  ajaxRequest.done((response, textStatus, jqXHR) => {
    alert('Submitted successfully');
  });

  ajaxRequest.fail(() => {
    alert('There is error while submit');
  });
});

We call the submit method with a callback.

The callback has the code to get the value from the form and then make an Ajax request.

First, we call event.preventDefault() to prevent the submission of the data with the default submission behavior.

We get the form’s value with:

const data = $(this).serialize();

this is the form element.

Next, we call jQuery’s ajax method to make the request for the form values to submit.

The url , type , and data properties are the same.

Then we can listen for the result with the done method to get the response when it’s successful.

We have the callback with the responnse parameter to get the response.

textStatus gets the status text.

jqXHR has the XmlHttpRequest object.

We also have the fail method to listen for any failures.

The fail callback will be called when there’s a network error.

How to Break Out of jQuery each Loop

We can return false in the callback by writing:

$.each(array, (index, value) => {
  if(value === "bar") {
    return false;
  }
});

We loop through an array with each .

In the callback, we get the index with the array index.

value has the value of the entry being iterated through.

We check that if value is 'bar' , then we return false to end the loop.

Conclusion

We can check for attribute values with the attr method.

To preload images, we can create image elements and set the src property of them with the image URL.

We can submit form input values with Ajax by serializing the values and then make the request.

And we can break out of an each loop with return false .