Common Uses for jQuery
October 7, 2021
1 min read
jQuery is one of the more popular JavaScript utilities, mostly because of how useful it can be. It's cross-browser so you don't have to worry about annoying browser differences in JavaScript implementations. With the popularity of React, I find that I use jQuery less these days, however, it can still be useful on a wide range of projects.
Here are a few of my favorite uses:
Execute code when the page is loaded
$( document ).ready(function() {
// code stuff here
});
Copy
OR
$(function() {
// code stuff here
});
Copy
Find all links on a page and alter the ones that lead to external websites
$('a')
.filter('[href^="http"], [href^="//"]')
.not('[href*="' + window.location.host + '"], [href*="www.exempt-domain.com"]')
.attr('rel', 'noopener noreferrer')
.attr('target', '_blank')
.addClass('link-external');
Copy
Find a value in an array
// search in an array
var test_array = ["one", "two", "red", "blue"];
var idx = $.inArray("two", test_array));
// search in a string
var test_string = "this is a string";
var idx = $.inArray("s", test_string);
Copy
I'll add more to the list as I remember them…