Categories
jQuery Tips

jQuery Tips — KeyPress, CSS and Important, and Options

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.

How to Apply !important Using .css()?

We can apply the !important in various ways.

One way to apply it is to create our own CSS rule for a class and then apply that class to our element.

For instance, we can write:

.important { width: 100px !important; }

To add a CSS property with the !important directive.

Then we call addClass to add the class.

For instance, we can write:

$('#foo').addClass('important');

We applied the important class to an element with ID foo .

Likewise, we can call attr to add the style attribute value to our element.

For example, we can write:

$('#foo').attr('style', 'width: 100px !important');

We set the style attribute with our own rule and the !important directive with the CSS rule.

Also, we can pass in 'cssText' as the first argument of css to apply the CSS rule with !important .

For instance, we can write:

$('#foo').css('cssText', 'width: 100px !important');

With 'cssText' as the first argument, we can apply !important .

Detect Pressing Enter on Keyboard Using jQuery

We can detect the pressing of the Enter key by listening to the keypress event when jQuery.

For instance, we can write:

$(document).on('keypress', (e) => {
  if (e.which === 13) {
    console.log('enter is pressed');
  }
});

We get the key that’s pressed with the which property.

13 is the code for the Enter key, so we can compare it against that.

There’s also the keycode property that may be available in some browsers.

So we can write:

$(document).on('keypress', (e) => {
  if (e.which === 13 || e.keyCode === 13) {
    console.log('enter is pressed');
  }
});

A more modern alternative, which is probably the best choice, is to use the key property.

For instance, we can write:

$(document).keypress((event) => {
  if (event.key === "Enter") {
    // ...
  }
});

The key property has the text of the key that’s pressed, rather than the numerical code.

This is clearer than the other alternatives.

jQuery Ajax Error Handling and Show Custom Exception Messages

We can get the error in the error handler.

For instance, we can write:

$.ajax({
  type: "post",
  url: "/login",
  success: data, text) => {
    //...
  },
  error: (request, status, error) => {
    console.log(request.responseText);
  }
});

We make the request with the ajax method.

type has the request type.

url is the URL.

success is the success handler.

error is the error handler.

request has the responseText property with the response text of the request.

status has the status code.

error has the errors from making the request.

Errors only appear when there’s a network error when making a request.

Select a Particular Option in a Select Element in jQuery

To select a particular option in a select element, we can get the option with the value attribute.

For instance, we can write:

$('select option[value="foo"]')

We get the option with the value attribute set to foo .

If we want to get the option by index, we can use the eq pseudoelement.

We can write:

$('select option:eq(1)')

Also, we can get an option element by text by using the contains pseudoelement.

For instance, we can write:

$('select option:contains("foo")')

We use the contains pseudoelement to search for an element with the given text.

And we can call filter to return the option elements with the given text.

For instance, we can write:

$('select option')
  .filter((e, i) => {
    return $(e).text() === "foo"
  })

We get the option elements.

In the callback, we have the parameter e , which is the option element object for the select element.

The text method returns the text of the option element.

To make the item with the given value selected, we can do it in various ways.

For instance, we can write:

$('select option[value="foo"]').attr("selected", "selected");

We add the selected attribute to the option element.

To make our lives easier, we can use the val method to set the value of the select element.

For example, we can write:

$('select').val('foo');

We set the value to foo so that the option element with the value foo is selected.

Conclusion

There are ways to apply the !important directive to our CSS.

Also, there’re many ways to select an option element with the value or text.

And we can get the key that’s pressed by listening to the keypress event.

Categories
jQuery Tips

jQuery Tips — Ready State, Sizes, and Ajax

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.

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.