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 .

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.