Categories
jQuery Tips

jQuery Tips — Checkbox, Click Outside, Append Elements

Spread the love

l)

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 if an Element is Hidden in jQuery

There are a few ways to check if an element is hidden with jQuery .

We can either look for visible or hidden pseudoelement.

For instance, we can write:

$(element).is(":visible");

or:

$(element).is(":hidden");

We can also check for the display and visibility selectors.

For instance, we can write:

if ($(element).css('display') === 'none' || $(element).css("visibility") === "hidden"){
  //...
}

Watching Progress for File Uploads

We can watch the progress of file uploads by adding an event listener to for the progress event on the xhr object.

For instance, we can write:

$(':button').on('click', () => {
  $.ajax({
    url: '/upload',
    type: 'POST',
    data: new FormData($('form')[0]),
    cache: false,
    contentType: false,
    processData: false,
    xhr: () => {
      const myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        myXhr.upload.addEventListener('progress', (e) => {
          if (e.lengthComputable) {
            $('progress').attr({
              value: e.loaded,
              max: e.total,
            });
          }
        }, false);
      }
      return myXhr;
    }
  });
});

We set the url for the upload.

type is the request type.

data is data we’re uploading, which is the FormData instances created from the form element.

cache disables caching if it’s set to false .

contentType is set to false to prevent it from setting the content-type header.

processData set to false tells jQuery not to convert the data.

Then we have an xhr property to get the xhr object.

Then we heck for the upload property.

We then call addEventListener method to watch for the progress event.

This let us watch for the uploaded progress and the total file size for the upload with the loaded and total properties.

“exists” Function for jQuery

We can check the length property to check if there any elements with the given selector is bigger than 0.

For instance, we can write:

if ($('.element').length > 0) {
  //...
}

We check if elements with class element exist with jQuery and see if the length is bigger than 0.

Find Which Radio Button is Selected via jQuery

We can find which radio button is selected with jQuery.

To do that, we can write:

$('input[name=radioName]:checked', '#someForm').val()

We check if the checkbox in the form with ID someForm is checked.

Then we can check that the input with the given name inside the form is checked.

Detect a Click Outside an Element

We can stop the progapation of the click event on the element that we want to check the outside of.

Then we can watch for clicks in the window to check if the click is outside the element.

For example, we can write:

$(window).click(() => {
  // hide the menu
});

$('#menu').click((event) => {
  event.stopPropagation();
});

We can also focus the menu container if it’s clicked.

And hide it if we click away.

For instance, we can write:

$("#menuContainer").click(function() {
  $(this).focus();
});

$("#menuContainer").blur(function(){
  $(this).hide();
});

Add Table Row in jQuery

To add a table row in jQuery, we can call after with an HTML string in the argument.

Given that we have the following table:

<table id="table">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

We can write:

$('#table tr:last').after('<tr>...</tr><tr>...</tr>');

We select the last table row, and then use the after method to add the new rows as siblings after the last tr .

Later versions of jQuery after 1.4, also has the append method to let us append child elements into a given element.

To append rows to a table, we can write:

$('#table').append('<tr><td>foo</td><td>bar</td></tr>');

We just call append without looking for the last table row.

Scroll to Element with jQuery

We can scroll to an element with jQuery by using the animate method and pass in an object with the scrollTop property with the item that we want to scroll to.

For instance, we can write:

$("#button").click(() => {
  $([document.documentElement, document.body]).animate({
    scrollTop: $("#scrollToElement").offset().top
  }, 2000);
});

When the button with ID button is clicked, we call the animate on the body or document element.

Then we call animate to animate the scrolling to the element with ID scrollToElement .

We get the value of the top position so that we can scroll to there.

Conclusion

There are various ways to check for the checked value of a checkbox.

Also, we can watch the progress of file upload with the xhr object we can get from jQuery Ajax.

We can add a table row with various methods.

Also, we can scroll to an element with the animate method.

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 *