Beginner

How to Use jQuery’s .select() Method

jQuery’s .select() method is not a super popular or commonly used jQuery event method, but it can be very useful. A select event occurs when text within a text area or text input field is selected (highlighted) by a user using the cursor. Basically, the only time you would use it is if you want a particular effect to happen or code to change as a direct result of a user selecting text written, either text by themselves or text that exists as the result of it being assigned the value for the elements in question, within a text area or text input field.

What follows is a look at the basic syntax, which is similar to that of many other jQuery event methods:

$(selector).select(function)

You can choose to attach a function to the select event, or you can choose to leave the parameter parentheses blank. To see what it might look like with a function attached, check out the code snippet example below.

To better understand how this jQuery event method works, we’re going to show you how you would use it in a realistic context. In the example below, the code demonstrates how the .select() method can be used to trigger an alert message on your page:

$("textarea").select(fucntion(){
   alert("You highlighted some text -- good job!");
})

So in the example above, when any text from within a text area is selected or highlighted (whether it be text entered by the user or text that was already there), an alert will pop up on the page that says “You highlighted some text — good job!” It’s important to remember that because of the way this code is written, this alert will appear each and every time that text is selected or highlighted within any text area element on the page. If you’d like for that to be different, then be sure to customize the code to suit the needs of your own project.

jQuery Bubbling Text Effect

This tutorial will demonstrate how to use CSS, jQuery, and JavaScript to create a really simple and cool text effect where it appears as though there are bubbles forming behind the text. After forming, the bubble float above the text before they disappear. This tutorial was inspired by a code snippet that originally appeared on CodePen.

Screen Shot 2017-04-15 at 4.08.17 PM

The HTML

To start creating this effect, first you’ll need some HTML. We’ve included our text in an h1 tag which is wrapped in a div. Check out our code below:

<div class="bubbles">
<h1>Bubble Text!</h1>
</div>

The CSS

Even though jQuery is the most important part of getting the animated bubbles to work for this effect, this snippet would be incomplete without some styling. In the CSS code snippet below, we define things like the background-color, the font-family, and the round shape of the bubbles. Make sure you don’t skip this step, but feel free to customize the code to your liking.

body {
background-color: #3498db;
}
.bubbles {
display: inline-block;
font-family: arial;
position: relative;
}
.bubbles h1 {
position: relative;
margin: 1em 0 0;
font-family: 'Lemon/Milk', cursive;
color: #fff;
z-index: 2;
}
.individual-bubble {
position: absolute;
border-radius: 100%;
bottom: 10px;
background-color: #fff;
z-index: 1;
}

The jQuery

All that’s left to create this cool effect is the addition of some jQuery code. The jQuery is very straightforward – we need to create two arrays, one blank one that will determine the positioning of the bubbles, and another that is populated and will help determine the size of each bubble. Then, we’ll need to write a function that selects random array elements, and another that generates a new selection every 350 milliseconds. Then we have some code that will append the bubbles to the HTML so that they appear in the viewport, and finally we need a final callback function to remove the bubbles from the viewport, so that a huge collection of bubbles doesn’t accumulate at the top of the page. The original author of the aforementioned CodePen snippet annotated the jQuery code very well, so we’ve left his meticulous notes in the code to help you follow the steps as you read them.

// Created for an Articles on:
// https://www.html5andbeyond.com/bubbling-text-effect-no-canvas-required/
jQuery(document).ready(function($){

 // Define a blank array for the effect positions. This will be populated based on width of the title.
 var bArray = [];
 // Define a size array, this will be used to vary bubble sizes
 var sArray = [4,6,8,10];

 // Push the header width values to bArray
 for (var i = 0; i < $('.bubbles').width(); i++) {
 bArray.push(i);
 }

 // Function to select random array element
 // Used within the setInterval a few times
 function randomValue(arr) {
 return arr[Math.floor(Math.random() * arr.length)];
 }

 // setInterval function used to create new bubble every 350 milliseconds
 setInterval(function(){

 // Get a random size, defined as variable so it can be used for both width and height
 var size = randomValue(sArray);
 // New bubble appeneded to div with it's size and left position being set inline
 // Left value is set through getting a random value from bArray
 $('.bubbles').append('<div class="individual-bubble" style="left: ' + randomValue(bArray) + 'px; width: ' + size + 'px; height:' + size + 'px;"></div>');

 // Animate each bubble to the top (bottom 100%) and reduce opacity as it moves
 // Callback function used to remove finsihed animations from the page
 $('.individual-bubble').animate({
 'bottom': '100%',
 'opacity' : '-=0.7'
 }, 3000, function(){
 $(this).remove()
 }
 );

 }, 350);

});

Now you can experiment with this very cool effect — customize the speed, size of the bubbles, colors, etc — and add it to any of your next projects!

 

Using jQuery to Get Page Load Time

If you ever find yourself needing to know how long it takes for one of your pages to load, we’ve got the snippet for you. There are many reasons you might want to understand how long a page load takes — doing this might especially appeal to developers who have got their pages loaded with ads, and want to test how much they’re slowing down the site. You can try loading the page yourself, but sometimes to the naked eye it can appear as if the page has loaded, when really scripts are still trying to be fetched and ads have yet to be loaded. Under these circumstances, it’s easier to just test it out using code.

See below for the code snippet:

var start = new Date(); 
jQuery.ready(); 
var end = new Date(); 
var difference = (endTime - startTime) / 1000; 
alert("document.ready time: " + difference + " seconds");

In the code above, we first record the time (using the Date method) when the page is requested and begins to load. This line must go at the top of the code. Then, one the page is loaded (that’s what the jQuery.ready() line is for) we fetch the time again. We find the difference between the two and divide the answer by 1000, because the time is measured in milliseconds and we want our answer to be in seconds for the purpose of this tutorial (but milliseconds is totally fine too if you’d rather your answer be in that format — just remove the division part of the equation!) and set the time to the variable “difference”. From there, we use an alert to let us know the time it took for the page to load by referencing the difference variable. If you don’t want the time difference to appear as an alert, you can log it to the Console or add it to your HTML — whichever works best for you and your project.

3 Useful jQuery Snippets for Handling Table Data

Do you want the ability to be able to dynamically edit and manage your tables? With jQuery, it’s pretty easy to get data and change table elements dynamically using only a few lines of code. The snippets below will show you how to add a new row to your table, how to retrieve all values in a row from a click event, and how to count the number of rows that a table has by using simple and lightweight plain jQuery code.

Counting Table Rows

If you find yourself wanting to know how many rows are in your table, you can use the following snippet to let jQuery do all the calculations for you:

$("#my-table").after(function () {
 console.log($('tr', this).length + " rows.");
});

The code above logs to the console how many rows are in your table with the ID of “my-table”, and it only takes two lines of jQuery to do it!

Get Row Values from Click Event

What if you want to be able to click on a table row and have all the data within the cells of that row be logged to the console? Achieving this is actually pretty straightforward. Check out the code snippet below to see how it’s done using jQuery:

$(“#my-table tbody”).on(“click”, “tr”, function () {
var rowdata = $(this).closest(‘tr’).find(‘td’).map(function () {
return $(this).text();
}).get().join();
console.log(rowdata);
});

In only 5 lines of jQuery, you can log all the data of a table row to your console just by clicking on it. As you can see, the trigger is a click event, and then we use other jQuery methods like find, map, and join events to gather all the data before logging it to the console.

Add Row on Click Event

This code will add a new row below any row that you click on using jQuery. Be sure to customize the row variable so that the amount of cells the new row has matches the amount of your table. Check out the code snippet below.

$(function () {
 $("#my-table tbody").on("click", "tr", function (e) {
 if (e.target.type != "text") {
 var row = $("<tr><td><input /></td><td>-</td><td>-" +
 "</td><td>-</td><td>-</td></tr>");
 $(this).after(row);
 }
 });
});

 

How to Use jQuery’s .delay() Method

jQuery’s .delay() method is one that can be used, probably quite obviously, to delay code from being executed. In particular, it can be used to make certain actions or animations last longer because the code is delayed. As a developer, there are a bunch of different reasons that you might want to use a delay. Maybe you want things to load or animate a certain amount of time after a page load or an event trigger. Using this method is also a really easy way to have something happen, have a short delay, and then go back to the way that it was.

For example, if you want a div to hide after a certain trigger event and then show again after a certain delay, you would use the delay method in a similar context to the way its used in the snippet below:

$("div").click(function{
    $(this).hide().delay(5000).show();
})

So in the snippet above, the div will be hidden after you click it for 5000 milliseconds (5 seconds) and then after the 5000 ms delay, it will appear again. The first line with the .click() method is the trigger event, which is followed by a function that executes the hide/delay/show events. So the div is hidden, then there is a 5 second delay where no code is executed, and then it is shown again.

This is just one example of how to use this versatile method. The speed parameters taken by the method (in the example above it’s “5000) can either be a number value (in milliseconds) or a fixed value (slow or fast). This is quite important, as it determines the length of time of the delay and, in the example above, the duration of the hide/show effect. Remember when using number values that the time is measured in milliseconds, so multiply the amount of seconds you want the delay to last by 1000 to be sure that you’ve got the right time.

How to Use JavaScript to Detect Devices

The great thing about JavaScript is how it enables you to dynamically make changes to your code based on certain events or conditions. One such condition that might cause you to want to make changes to  your code (or at least some slight modifications) is which type of device is being used to view your projects or web pages. This is because each mobile device (iPhone, Android, iPad, etc) have different dimensions and aspect ratios that unfortunately don’t always respond to your code and display your designs in exactly the way you’d like. Luckily, JavaScript provides a very easy and simple way to test for a particular type of device and execute some code based on whether or not your user is using the particular device you’ve singled out.

Check out the snippet below to see how it works:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // Do something
} else {
 // Do something else
}

Obviously, the snippet as it stands wouldn’t really do anything. You ned to choose one of the 7 device options provided and use that with the .test() method to test for that one particular device you’re trying to compensate for (if you want to set code specific to another type of device, you’ll have to add another if statement). Then, once you’ve selected the type of device you’re trying to write code for, you can insert the code you want to be executed into the if statement. You can be trying to change the color, shape, or dimensions your elements so that they better fit within the viewports of your chosen type of device, or you can simply use the code to troll iPhone users (see example below) — it’s totally up to you.

Check out the example below to see one way in which you can use the device detector code.

if( iPhone.test(navigator.userAgent) ) {
 alert("Androids Rule");
} else {
 alert("Congratulations, you're not using an iPhone");
}