Categories
jQuery Tips

jQuery Tips — Scrolling, Drop Downs, props vs attr

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.

Scroll to Element with jQuery

jQuery has a scrollTo method to scroll to a given element without trouble.

This is a jQuery plugin that we can add from http://demos.flesler.com/jquery/scrollTo/

We can install by writing:

<script src="//cdn.jsdelivr.net/npm/jquery.scrollto@2.1.2/jquery.scrollTo.min.js"></script>

or:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/2.1.2/jquery.scrollTo.min.js"></script>

in our HTML.

Or we can download it manually from those locations or from the releases page (https://github.com/flesler/jquery.scrollTo/releases).

For instance, we can write:

$('body').scrollTo('#target');

to scroll to the element with the ID target .

We can also scroll to a given distance by writing:

$('body').scrollTo(500);

to scroll down to the given number of pixels.

There are various options we can set the control the scrolling.

scrollTarget is an element, string, or number that indicates the scroll position.

offsetTop is the number that indicates the additional spacing above the scroll target.

duration is the duration of the scrolling animation.

easing is a string that indicates the easing function for use with the function.

complete is a function to call once the animation is done.

Get Selected Text from a Drop-Down List (select Element) Using jQuery

We can call the text method to get the selected text from a drop-down list of the selected element.

For instance, we can write:

$("#drop-down option:selected").text();

We get the selected option with the selected pseudoelement and call the text method to get the text content of the option.

We can also write:

$("option:selected", $("#drop-down")).text();

to get the selected option from the same dropdown.

Also, we can call find with the patent to get the child element we want:

$('#drop-down').find('option:selected').text();

There’s also the children method to do the same thing:

$("#drop-down").children(":selected").text();

We get the same child element with children .

Also, we can watch for changes with the change method.

For example, we can write:

$("#drop-down").change(function(){
  console.log($('option:selected', $(this)).text());
});

We watch the dropdown for changes and log the selected value from the dropdown by getting the dropdown and watching the selected option child element.

.prop() vs .attr()

prop is preferable to attr in most cases.

prop does what attr used to do.

So it should work in most cases if we replace attr with prop .

Properties are simple to deal with than attributes.

attributes can only be a string but properties can be of any type.

checked would be a boolean for example.

With both the property and attribute exist, then updating one will also update the other.

With the prop method, we don’t have to check attributes using the attr method anymore.

Disable or Enable Input with jQuery

We can disable or enable an input with jQuery.

To do that, we can use the prop method to do so.

For instance, we can write:

$("input").prop('disabled', true);

to disable the input and:

$("input").prop('disabled', false);

to enable it.

We can also write:

$("input")[0].disabled = true;

or:

$("input")[0].disabled = false;

to disable or enable an input element.

Get the Children of the $(this) Selector

To get the children of the this selector, we can use the find method.

For instance, to get all the divs of this , we can write:

$(this).find('div');

If we want to get an element right next to whatever element is set as this , we can write:

$(this).next();

To get the direct children of this, we can also write:

$('> .child-class', this)

or we can use children to get the children:

$(this).children('div')

We can also get the n-th child by writing:

$(this).children('div:nth(n)')

To get the last child, we can write:

$(this).find("div:last-child")

Select an Element with Multiple Classes in jQuery

We can get an element with multiple classes by passing the string with the given selector.

For instance, we can write:

$('.a.b')

We get the class with both classes a and b without spaces.

We can do the same thing with the filter method:

$(".a").filter(".b")

We get the items with class a and then we call filter to get the elements with class b .

Conclusion

We can use a scroll to plugin to help us scroll to an element easier.

Also, we can get the text of a dropdown list.

prop is preferred to attr .

And we can get elements that have multiple classes added to it in multiple ways.

Categories
jQuery Tips

jQuery Tips — Checkbox, Click Outside, Append Elements

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.

Categories
jQuery Tips

jQuery Tips — Checkbox and Uploads

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.

Return the Response from an Ajax Call

Synchronous Ajax calls aren’t recommended since it blocks the other parts of the app from running.

This is because JavaScript is single-threaded.

To make a synchronous Ajax call with jQuery, we can set the async option to false .

For example, we can write:

const foo = () => {
  const jqXHR = $.ajax({
    //...
    async: false
  });
  return jqXHR.responseText;
}

It’s better to make an async Ajax call with it instead.

For instance, we can write:

const login = () => {
  return $.ajax({
    url: '/login',
    data: {
      username: $('#username').val(),
      password: $('#password').val()
    },
    type: 'POST',
    dataType: 'json'
  });
}

This returns a deferred object.

So we can run code after this is done by calling done and passing a callback in it.

To handle errors, we can call fail and pass a callback to that.

So we can write:

const login = () => {
  return $.ajax({
    url: '/login',
    data: {
      username: $('#username').val(),
      password: $('#password').val()
    },
    type: 'POST',
    dataType: 'json'
  });
}

login()
  .done((res) => {
    //...
  })
  .fail((err) => {
    //..
  });

Check Whether a Checkbox is Checked in jQuery

We can use the is method to check for the checked pseudoelement.

For instance, we can write:

$("#isSelected").is(':checked')

We get the checkbox with the ID isSelected and check for the checked pseudoelement.

Also, we can use the prop method to do the same thing:

$('#isSelected').prop('checked')

The attr method also works:

$("#isSelected").attr("checked")

To watch for changes, we can write:

$("#checkbox").change(function() {
  if($(this).prop('checked')) {
    alert("checked");
  } else {
    alert("unchecked");
  }
});

We watch for changes with the change method.

Then we use the prop method to check for the checked attribute.

There’s also the toggle method:

$("#checkbox").toggle(
  $("#selected").prop("checked")
);

We watching for toggling of the checkbox with the toggle and get the checked property.

Setting the Checked State for a Checkbox with jQuery

There’re several ways to get toggle the checkbox.

For instance, we can use the prop method:

$('#checkBox').prop('checked', true);

to toggle the checkbox to be checked.

And we can write:

$('#checkBox').prop('checked', false);

to make it unchecked.

We can also set the checked property.

For instance, we can write:

$('.checkBox')[0].checked = true;

and:

$('.checkBox')[0].checked = false;

to make it checked and unchecked respectively.

There’s also the attr method to make the checkbox checked or unchecked.

For instance, we can write:

$('.checkBox').attr('checked', true);

and:

$('.checkBox').attr('checked', false);

to make our checkbox with the class checkBox checked or unchecked.

attr is deprecated.

We can use the prop method to set the checked value:

$(".checkBox").prop('checked', true);

and:

$(".checkBox").prop('checked', false);

We can also uncheck a checkbox by calling removeAttr :

$('.checkBox').removeAttr('checked')

Also, we can trigger a click event for the checkbox:

$("#checkBox").click();

And we can write:

$('.checkBox').attr('checked', 'checked');

to set the 'checked' value to be checked.

event.preventDefault() vs. return false

jQuery event handlers can have e.preventDefauly and return false called.

For instance, we can write:

$('a').click(function (e) {
  // ...
  e.preventDefault();
});

or:

$('a').click(function () {
  // ...
  return false;
});

return false inside a jQuery event handler does the same thing as e.preventDefault() and e.stopPropagation together.

e.preventDefault() prevents the default behavior of the event from occurring.

e.stopPropagation() prevents the event from bubbling up.

In non-jQuery event handlers, return false doesn’t stop the event from bubbling up.

Upload Files Asynchronously

To upload a file with jQuery, we can set the data property to the FormData instance.

For instance, we can write:

$.ajax({
  url: '/upload',
  type: 'POST',
  data: new FormData($('#formWithFiles')[0]),
  processData: false,
  contentType: false
})
.done(() => {
  console.log("success");
})
.fail(() => {
  console.log("error");
});

formWithFiles is an ID of a form with a file input.

We just set it as the value of data .

And we set the url and type of the request.

processData set to false prevents it from converting the form values to a query string.

contentType set to false tells it not to set the data type.

Conclusion

We can check for the checked value of a checkbox in various ways. Also, we can toggle it on and off in multiple ways. Uploading files can be done by setting the form data.

Categories
HTML JavaScript jQuery

How to Find an Element by Name with jQuery

We can find an element with the given name with jQuery by using the $ itself.

For instance, if we want to find something with the name foo, we can write:

$('[name=foo]')

The general form of this CSS selector is:

[attribute=value]

In the example above name is the attribute and foo is the value of the name attribute.

Then that will return the element with the name foo.

Once we did that, if the element exists on the page, then we can do anything with it like adding/removing classes, adding/removing styles, and so on.

Categories
HTML JavaScript jQuery

How to Find an Element by ID with jQuery

We can find an element with the given ID with jQuery by using the $ itself.

For instance, if we want to find something with ID foo, we can write:

$('#foo')

Then that will return the element with the ID foo.

Once we did that, if the element exists on the page, then we can do anything with it like adding/removing classes, adding/removing styles and so on.