Beginner

6 Unique jQuery Plugins for Background Effects

Ever feel like the backgrounds of your web pages always end up being just a little bit boring? As a web developer, it can be hard to determine how to add some life into your backgrounds, and it can also be time consuming to write your own code to do so. If you’re looking for a quick fix to spice up your projects, check out this curated list of 6 jQuery plugins that will add fun, free, and unique touches to the background of your pages.

1. Particleground

Screen Shot 2017-02-16 at 3.35.47 PM

 

Particleground is a really fun plugin that adds subdued yet animated moving particle systems to the background of any of your web pages. The particles have a light shade so as not to distract from your pages’ content. The plugin comes with the option to enable the particles to move in correspondence with your cursor.

2. BgSwitcher

Screen Shot 2017-02-16 at 3.43.19 PM

 

This lightweight, easy to use plugin generates a slideshow of images to function as the background of a page. The slideshow flips through the images using smooth animated transitions. To see it in action, check out the demo.

3. Vide

Screen Shot 2017-02-16 at 3.45.27 PM

If you’d like to use a video as the background for your web pages, this plugin is an awesome option for doing so. It couldn’t be easier to use and it’s supported on all desktop browsers (there’s no support for iOS, however, and a cover photo will be displayed when your page is viewed on an iOS device). You can customize volume, playback rate, if you want the video to be on a loop, and much more.

4. Adaptive Backgrounds

Screen Shot 2017-02-16 at 3.48.15 PM

Adaptive Backgrounds is a fun little plugin that chooses the background colors of your web pages or block-level elements based on the dominant colors of the images inside of them. Definitely a cool plugin to add to your projects or to just play around with!

5. Vegas Background Slideshow

Screen Shot 2017-02-16 at 3.55.53 PM

Another background slideshow plugin, this one includes a sort of Ken Burns effect applied to the images, and very nice and smooth fading transitions. Great for showcasing hi-res images.

6. Geometry Angle

Screen Shot 2017-02-16 at 4.00.06 PM

Geometry Angle is a plugin that adds a 3D shading effect to your backgrounds. The effect, while being 3D, is also animated, so it looks as though the shapes and shades are always slowly moving about your page.

How to Find the Coordinates of Your Mouse Position

Did you know you can use jQuery to find the coordinates of your cursor? It only takes a few lines of code to get the x and y coordinates of where the mouse is positioned on a page. With these coordinates, you can execute other functions and lines of code based on where the cursor is located on the page. It’s also just a cool trick to offer your users — for example, you can choose to allow them to click a button that will reveal the x and y coordinates of their mouse.

Check out the code snippet below to see how it’s done:

function cursorPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

Insert the above function into your code to reveal the values of the x and y coordinates of your cursor’s position. This code can be customized to be used however you like it — if you want to execute a function based on the cursor’s position, you’ll probably need an if statement. If you want to reveal the cursor’s coordinates to your users, you might want a click event (or some sort of trigger event) and code that will make the data available to the user (perhaps an alert box). The possibilities are endless.

Handy jQuery Code Snippets for Textboxes

Code snippets are great time savers as these are essentially just reusable pieces of code. Implementing client side validations can be done using jQuery, as well as some other basic tasks like clearing value or enabling and disabling textboxes. This post provides a list of useful jQuery code snippets for handling textbox related tasks with ease. These snippets are useful for validation, clearing out values on key stroke, copying one textbox value to another in real time and several other tasks. Check it out!

1. Clear input textbox value using ESC key

The ESC key is mainly used for cancelling your current process, closing popups, or clearing out input. If you wish to implement textbox value clearing when the ESC key is pressed, then following jQuery code will help you achieve this. It checks for the ASCII code of the key and if it matches with the ASCII code of the ESC key, then it simply clears the value of the textbox in focus. Like this:

$(document).ready(function() {
    $('input[type="text"]').keyup(function(e){
        if(e.keyCode == 27) {
            $(this).val('');
        }
    });
});​

2. Clear input textbox on page load

Following jQuery code will clear all the input-type textboxes, when DOM is ready. It loops through all the textboxes present on the page and within the loop, clearing its value.

$(document).ready(function() {
    $('input[type=text]').each(function() {
        $(this).val('');
});
});​

If you want to clear the value of the event in focus, then use the following jQuery code:

$('input[type=text]').focus(function() {
      $(this).val('');
   });

3. Allow only numbers in textbox

As part of some form validations, there may be a restriction that only allows numbers in the textboxes. For example, when the value represents age, price, number of days, etc. The following jQuery code will allow only numbers in the textbox with ID “txtNumber”. It uses the keydown event to detect the user input value’s ASCII code. In this case the ASCII code must be in a range of numbers. The following code allows keys like backspace for clearing the value and TAB keys for moving out of the textbox:

$(document).ready(function(){
   $("#txtNumber").keydown(function(e)
   {
       if (e.shiftKey)
           e.preventDefault();
       else
       {
           var nKeyCode = e.keyCode;
           if (nKeyCode == 8 || nKeyCode == 9) //Ignore Backspace and Tab
               return;
           if (nKeyCode < 95)
           {
               if (nKeyCode < 48 || nKeyCode > 57)
                   e.preventDefault();
           }
           else
           {
               if (nKeyCode < 96 || nKeyCode > 105)
                 e.preventDefault();
           }
       }
   });
});
4. Disable Cut, Copy and Paste operation

The following jQuery code will disable ‘cut’, ‘copy’ and ‘paste’ operations on the input text boxes. Using the jQuery .on() method, the ‘cut’, ‘copy’ and ‘paste’ events are attached to all input text boxes and the code will prevent the default behavior, like this:

$(document).ready(function(){
  $('input[type="text"]').on("cut copy paste",function(e) {
      e.preventDefault();
  });
});

5. Set focus on the first textbox of the page

The following code will set the focus to the very first enabled input textbox on the page, when the page is originally loaded:

$(document).ready(function(){
   $('input[type=text]:enabled:first').focus();
});

But if the very first textbox is not visible, for example if it is set to “display:none;” then the above code will fail. So the best solution is to check for visible and enabled textboxes and then set the focus. Like this:

$(document).ready(function(){
   $('input[type=text]:visible:enabled:first').focus();
});

6. Turn off autocomplete for all textboxes

These days most modern browsers cache every single input and smartly houses a list based on the input, like a list of email addresses for an email address inbox. When you visit any website, the browsers will display a list of all previously used inputs. When this is not necessary for your work, it can be quite frustrating. If you wish to disable autocomplete for all textboxes present on the page, the following jQuery code will help:

$(document).ready(function(){
  $('input[type="text"]').attr("autocomplete", "off");
})

Though you can set the autocomplete=”off” attribute on textboxes, you will have to set it for all the text boxes and that takes time. Instead, use the single line of jQuery code and you can achieve the same for all the text boxes present on the page at once!

7. Copy value from one textbox to another while typing

If you wish to copy the content of one input textbox to another in real time, the following jQuery code will do the job. This jQuery code attaches a keyup event to the source and then assigns its value to the destination textbox:

$(document).ready(function() {
    $('#txtSource').keyup(function(e) {
        $('#txtDestination').val($(this).val());
    });
});

The above code will copy the text from one textbox to another. But if you wish to sync multiple textboxes then assign a CSS class to every textbox which should be part of syncing and then bind the keyup event to the CSS class selector. The HTML code will look something like this:

<input type="text" id="txt1"/>
<input type="text" id="txt2" />

Below is the jQuery code that binds the event to copyText and assigns the same value to all the elements that have copyText CSS class:

$(document).ready(function() {
    $('.copyText').keyup(function(e) {
        $('.copyText').val($(this).val());
    });
});

8. Convert textbox value to uppercase

The following jQuery code will convert the textbox’s value to uppercase lettering when the focus goes out of the textbox. toUpperCase() is a JavaScript method which converts the string to upper case letters:

$(document).ready(function() {
    $('#txtSource').blur(function(e) {
        $(this).val($(this).val().toUpperCase());
    });
});

You can also set to lower case using the toLowerCase() method. Like this:

$(this).val($(this).val().toLowerCase());

9. Change textbox width on focus and restore on focus out

The following jQuery code will change the textbox width to 350px and then restore again to 200px when the focus goes out. This code makes use of the jQuery animate method, which provides simple animation while changing width:

$(document).ready(function() {
  $('#txtValue').focus(function() {
    $(this).animate({ width: '300px'}, 'fast');
  });
  $('#txtValue').blur(function() {
    $(this).animate({ width: '200px'}, 'fast');
  });
});

Using the animate() method, duration can be assessed. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings ‘fast’ and ‘slow’ can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

10. Disable all textboxes

The following jQuery code will disable all the textboxes present on the page by setting the “disabled” property to true:

$(document).ready(function() {
    $('input[type="text"]').prop("disabled", true);
});

If there are multiple forms on your page and you wish to disable textboxes of a particular form, then all you need to do is supply the form Id to jQuery selector. Like this:

$(document).ready(function() {
    $('#frm1 input[type="text"]').prop("disabled", true);
});

In this case, all the input textboxes for “frm1” will be disabled.

 

To sum up, these jQuery code snippets for input textboxes are handy when implementing validations, disabling and enabling, setting focus for providing a better user experience and, from a security point of view, to disable copying. These tiny snippets can save you valuable minutes, and allow you to complete tasks with ease!

How to Refresh One Section of a Page

There are plenty of times where you might want to refresh only part of your page’s content, leaving the static content to be, well, static, and refreshed at the user’s discretion. Reloading an entire page on a user can be jarring, confusing, and doesn’t make for a great user experience. However, if your page features timely news stories or breaking news, featured content that is updated often, or even promotional or dynamic content that you’d like to reload to give your users more opportunities to see everything you’ve got to offer, refreshing just these particular areas of a page is a good option. This way, you can make sure your targeted content is updated, without alienating any users.

If you’d like to reload just a section (or a few sections) of a page, you can do so relatively easily and simply with jQuery. Check out the lightweight snippet below to easily add this functionality to any of your projects:

setInterval(function() {
$("#reloadContent").load(location.href+" #reloadContent>*","");
}, 200000);

As you can see, in the example above, we’re choosing to refresh the #reloadContent element. If you’d like to refresh an element with a different class or ID (note: it’s probably wise to only refresh elements using their IDs, rather than classes, so you don’t accidentally end up refreshing several different elements at once),  you can simply replace the #reloadContent with the name of your chosen element. You can then use the second parameter of the function (in the example above, 200000) to set the amount of milliseconds that should pass in between the initial page load and when you want your content and elements to refresh. Remember — the time interval is in milliseconds, so be sure to keep that in mind when setting your refresh time, so it doesn’t end up refreshing too often.

Use this snippet as many times as you’d like in your code to refresh several different elements at different time intervals.

Form Validation Snippets: Email Validation with jQuery

With jQuery, it’s possible to write code that executes client-side validations for your forms and input fields. A common validation to make is to check whether or not an email address that’s entered into an email field is actually a valid email address (or at least in valid email address format). The following is a great snippet to use to perform your own client side email input validation without having to use a plugin:

(function ($) {

    $.fn.validateEmail = function () {
        return this.each(function () {
            var $this = $(this);
            $this.change(function () {
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if ($this.val() == "") {
                    $this.removeClass("badEmail").removeClass("goodEmail")
                }else if(reg.test($this.val()) == false) {
                    $this.removeClass("goodEmail");
                    $this.addClass("badEmail");
                }else{
                    $this.removeClass("badEmail");
                    $this.addClass("goodEmail");
                }
            });
        });
    };
})(jQuery);

The snippet above assigns the class “goodEmail” to a submission that’s in email format ([email protected]) and “badEmail” to submissions that aren’t, and if the .badEmail class is applied to the submission, it won’t be validated and the form will not submit.

Caching Elements in jQuery

If you cache your jQuery elements, it means that you store an element as a variable so that you can re-use that element without your jQuery having to re-query the DOM in search of it every time you want to apply some code to that element. It’s not always necessary, but in cases where you know you’ll be using certain elements a lot in your code, it’s not a bad idea to cache them, because that’ll help your code work faster and more efficiently.

Here’s how you would cache an element, it’s actually super simple! For this example, let’s cache a class called .main:

 var main = $(“.main”);

That’s literally all it takes to cache an element. Then when you want to use it later, you just have to refer back to the name that you gave you variable, like this:

 main.css(“color”, “blue”);

The code above will change the CSS so that the color of the text in the .main class is blue. You can cache as many selectors as you like and give the variables whatever name you like, and this should help keep your code light and clean.