Categories
jQuery Tips

jQuery Tips — Ready State, Sizes, and Ajax

Spread the love

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.

$(document).ready Equivalent Without jQuery

We can create our own function that acts like $(document).ready by checking the loading state of our app.

For instance, we can write:

function ready(callback){
  if (document.readyState !== 'loading') {
    callback();
  } else if (document.addEventListener)  {
    document.addEventListener('DOMContentLoaded', callback);
  } else {
    document.attachEvent('onreadystatechange', () => {
      if (document.readyState === 'complete') {
        callback();
      }
    });
  }
}

We check the readyState of of the document by comparing it to the 'loading' state.

If it’s not, then the DOM is loaded and we can call our callback .

If that’s not available, then we add an event listener for DOMContentLoaded and it’s loaded, which means the event is triggered, then we call our callback .

Otherwise, we watch for the readystatechange event with attachEvent . This is only used with IE 8 or earlier, so we may not need this.

Get the Size of the Screen, Current Web Page, and Browser Window

We can get the size of the screen by using the height and width methods.

For instance, we can write:

$(window).height();
$(window).width();

to get the height and width of the viewport respectively.

Also, we can replace window with document to get the height and width of the document .

So we can write:

$(document).height();
$(document).width();

Abort Ajax Requests Using jQuery

The XHR object returned by jQuery has the abort method to let us cancel the request.

For instance, we can write:

const xhr = $.ajax({
  type: "POST",
  url: "some.php",
  data: "first_name=james&last_name=smith",
  success: (res) => {
    alert(res);
  }
});

xhr.abort()

We get the xhr object returned by $.ajax and then we call abort on it to cancel it.

Get the ID of an Element Using jQuery

We can get the ID of an element with jQuery by using the attr method.

For instance, we can write:

$('.test').attr('id')

We get the ID of the first element with class test .

Also, we can get it through the DOM object by calling get or using brackets to get the DOM object.

For instance, we can write:

$('.test').get(0).id;

or:

$('.test')[0].id;

Or we can use the prop method by writing:

$('.test').prop('id')

Add Options to a Select from as a JavaScript Object with jQuery

We can add options to a select dropdown by using the append method to add the options objects as the child of select .

For instance, we can write:

for (const o of options) {
  $('#mySelect')
    .append(
      $("<option></option>")
        .attr("value", o)
        .text(o)
    );
}

We create the option elements with $ and add a value attribute and the text to the option element.

Manage a Redirect Request After a jQuery Ajax Call

Wed can manage a redirect request after a jQuery Ajax call by doing the redirect in the success callback.

For instance, we can write:

$.ajax({
  type: "POST",
  url: reqUrl,
  data: reqBody,
  dataType: "json",
  success: (data) => {
    window.location.href = data.redirect;
  }
});

We make a POST request with ajax .

We did that by passing in the URL and body.

We set the dataType to JSON to make a request with JSON payload.

Then in the success callback, we get the redirect URL from the response data, which is in the first parameter.

And we do the redirect by setting it to window.location.href .

Change the href for a Hyperlink Using jQuery

We can change the href for a hyperlink with the attr method.

For instance, we can write:

$("a[href='http://www.google.com/']").attr('href', 'http://www.example.com/')

We get the links with href set to http://www.google.com and replaced that with http://www.example.com .

attr takes the attribute name as the first argument and the value as the 2nd argument.

Conclusion

We can change the href of a link dynamically.

Also, we can get the width and height of the viewport or document.

Ajax requests can be aborted.

And we can add drop-down options dynamically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *