Beginner

How to Use JavaScript to Detect Browser

Wouldn’t it be nice if all of our code looked the same and worked the same no matter what browser our users are viewing our projects or web pages on? That’s the dream, right? Unfortunately, cross browser compatibility isn’t something that a site can achieve without adding some extra code.

There a few ways that you can use code to compensate for different browsers. You can us CSS selector browser hacks, which is a good option, especially if any changes you need to accommodate for are mostly cosmetic and can be fixed with CSS. For more dynamic browser selections, JavaScript is actually a valid way to go.

Below, you’ll find a code snippet that you can use to check for Internet Explorer, Chrome, Firefox, Safari, and Opera. The function checks for these browsers, and will execute any code you insert within the if/else if statements for each browser if the code is run on any of the browsers in question. Use the code to dynamically add classes to your HTML based on the browser, to send alerts to the user based on the browser, to trigger events based on the browser.

The code snippet is lightweight and straightforward, so even the most beginner coders should be able to add it to their projects. Play around with it and see if you can’t achieve that elusive cross-browser compatibility!

function BrowserDetection() {
    //Check if browser is IE
    if (navigator.userAgent.search("MSIE") & gt; = 0) {
        // insert conditional IE code here
    }
    //Check if browser is Chrome
    else if (navigator.userAgent.search("Chrome") & gt; = 0) {
        // insert conditional Chrome code here
    }
    //Check if browser is Firefox 
    else if (navigator.userAgent.search("Firefox") & gt; = 0) {
        // insert conditional Firefox Code here
    }
    //Check if browser is Safari
    else if (navigator.userAgent.search("Safari") & gt; = 0 & amp; & amp; navigator.userAgent.search("Chrome") & lt; 0) {
        // insert conditional Safari code here
    }
    //Check if browser is Opera
    else if (navigator.userAgent.search("Opera") & gt; = 0) {
        // insert conditional Opera code here
    }
}

How to Use jQuery’s Mouse Methods

jQuery has 4 event methods that have to do with cursor movement. The methods are .mouseenter(), .mouseleave(), .mouseup() and .mousedown(). All of these methods can be used to trigger events and execute code based on when and where the user’s cursor moves. In terms of syntax, they’re fairly simple and straightforward to use, but they can also be really versatile and used to achieve some pretty cool functionalities and effects.

In this tutorial, we’re going to go over how to use each of the mouse event methods. Take a look at the code snippets below to for examples of how to use them in the context of your code.

.mouseenter() and .mouseleave()

The .mouseenter() and .mouseleave() methods are two that are often used together. You can probably guess what they do, but here’s a brief explanation. The .mouseenter() method is triggered when the cursor enters the selected element (here, the word “enters” means that the cursor moves over the element), and the .mouseleave() method is triggered when the cursor leaves, or stops moving over, the selected element.

There are many different effects you can achieve with these two methods. To see an example of how you might use them, check out the code below:

$("h1").mouseenter(function(){
     $(this).css("color", "red");
})
$("h1").mouseleave(function(){
     $(this).css("color", "blue");
})

In the code snippet above, the color of the h1 element that the cursor moves over turns red when the cursor is on top of it. When the cursor moves off of it, the color of the h1 element changes to blue.

.mouseup() and .mousedown()

The .mousedown() event is triggered when the mouse button is pressed down over a selected element (essentially, this is very close to the .click() method), and the .mouseup() event occurs when the mouse button is released over a particular element. Basically, it’s a click and release type of deal. Like .mouseenter() and .mouseleave(), these two event methods are often used in conjunction with one another. To see an example of how you would use it, take a look at the code below:

$("p").mousedown(function(){
     $(this).css("color", "orange");
})
$("p").mouseup(function(){
     $(this).css("color", "green");
})

In the code snippet above, the text color of the p element changes to orange when it’s clicked, and green when the click is released.

How to Verify User Age with jQuery Code

If you’ve ever visited a site that’s selling a product that has certain age restrictions (for example, a site selling or representing an alcohol brand might prompt you to verify that you’re over 21 before you’re allowed access to the site), you might have come into contact with an age verification form. It turns out, that this type of form is a fairly easy one to validate, because all you need to do is prove whether it’s true or false that someone is older than the desired age cut off for access to your site.

The jQuery snippet you can use to validate this type of form is as follows:

$("#age-verify").submit(function() {
    var day = $("#day").val();
    var month = $("#month").val();
    var year = $("#year").val();
    var age = 21;
    var mydate = new Date();
    mydate.setFullYear(year, month - 1, day);
    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() - age);
    if ((currdate - mydate) & lt; 0) {
        alert("Sorry, only persons over the age of " + age + " may enter this site");
        return false;
    }
    return true;
});

The code above assumes that the only relevant information you’re collecting from your age verification form (here it has the id #age-verify – - be sure to change it to match the id of your own form) is the day, month, and year of your users birth. The age variable sets the minimum age of users allowed access to your site. For the purposes of this example, we’ve made the minimum age 21.

Using some simple arithmetic and an if else statement, the snippet above determines whether a person is over 21 by checking if the current date subtracted by the age variable is greater than zero. If it is, then they are allowed access to the site, and if it isn’t, they’re presented with a “Sorry, you’re not old enough” message. Of course, there’s nothing about this form that wouldn’t stop an under age user from simply lying about the year of their birth, but the same is true with implementations of this type of form across the board, including with big, international brands.

How to Use jQuery’s .queue() Method

jQuery’s .queue() method is one that is actually an effect method. The .queue() method can be used to show the length of the queue for a particular selected element. The queue is the list of functions in line to be executed on a single selected element. So if you’ve got an element with five different functions attached to it, then the queue length would be five. The .queue() method used in conjunction with the .length() method is what you can use to calculate the queue length in your jQuery code.

The syntax for using the .queue() method is as follows:

$(selector).queue(queueName);

A good way to understand how exactly you can use the .queue() method is to see it in a real world context, so check out the example below to see how you would use the method to find the queue length on a p element when a button is clicked:

$("button").click(function(){
     $("span").text(p.queue().length)
})

So to understand what’s going on in the snippet above, it helps to see some HTML:

<button>How many functions are attached to the paragraph below?</button>
<span></span>
<p>I have three functions in my queue.</p>

For the purposes of this tutorial, let’s pretend that isn’t way too much text to be in a button. In the jQuery code snippet above, when the button is clicked, text is dynamically added to the span tag through the .text() method that states the queue length of the p element. It’s actually pretty straightforward. In this case, let’s say the p tag has three functions in its queue, so what was once an empty span tag will say “3″ once the button is clicked.

Sometimes (but rarely) elements have more than one queue attached to them. This is the only case in which you’d need to use the queueName parameter that the queue method takes. In this case, you’d write the name of the queue you’d like to find out the length of as the parameter, but again, this occurs very rarely.

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 & lt; $('.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
        var styleElm = 'style="left: ' + randomValue(bArray) + 'px;';
        styleElm = styleElm + 'width: ' + size + 'px; height:' + size + 'px;"';
        $('.bubbles').append('<div class="individual-bubble"' + styleElm + '></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!