10
X

How to Use jQuery to Detect Devices

The great thing about jQuery 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, jQuery 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");
}

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 (example@example.example) 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.

How to Create a Simple Image Slider Using jQuery

Image sliders are useful for showing multiple images with cool animations to catch a user’s attention.  Having an image slider/slideshow is a very common functionality that you may find on any website. Creating a simple image slider is pretty easy and it can be implemented easily with jQuery. There are tons of plugins available for creating image sliders using jQuery plugins, but one should be careful while using jQuery plugins as jQuery plugins consumes bandwidth and may increase page load time. If things can be done with jQuery code, one should not use any plugin. In this post, let’s see how to create simple image slider using jQuery.

HTML Markup

 

First, let’s take a look at HTML markup.  There is a parent div element and a child div element which contains all the image tags. Here, the child div element tag will be used for rotation of the images in the jQuery code.

<div id="sliderContainer">
<div id="sliderWrapper">
<img src="img/1.jpg" />
<img src="img/2.jpg" />
<img src="img/3.jpg" />
<img src="img/4.jpg" />
<img src="img/5.jpg" />
</div>
</div>

CSS

Below CSS code, used for parent slide container and for the individual images. This code will set the width of slider container to 800 pixels. It’s important to note that overflow: hidden property is applied to hide other images except the current one, otherwise all images would be visible on the screen. One thing to also note here that if your images are greater than 800px then you may need to adjust the width property accordingly.

#sliderContainer {
  width: 800px;
  margin: 0;
  padding: 0px;
  position: relative;
  overflow: hidden;
}
#sliderContainer .slider {
  margin: 0;
  padding: 0;
  width: 800px;
  float: left;
  position: relative;
}

 

jQuery Code

First, define few variables.

  • The first variable curPos, indicates the current position and it is set to 0.
  • Second variable is slider which gets the references of all images with CSS class “.slider”.
  • Third variable is cntImages, which gets the count of total number of images which are part of slider.
  • And the fourth variable is sliderWidth, which gets the width of slider container.

There were 2 div element defined in the HTML markup sliderContainer and sliderWrapper. The logic of creating image slider is, assign the total width to sliderWrapper which is sliderWidth * cntImages. So in this case, this value comes to 4000px (800×5). But it won’t be visible on the screen as parent element is having overflow:hidden property.

Next, create a function called SlideImage, which will be called by setInterval function with delay of 2 seconds. This ensures that images rotates automatically. Inside this function,

  • First checks, if the current image is the last image. If yes, then set curPos variable to 0 so that first image is shown again. And if not, then we increment the value of curPos variable.
  • To show next image as part of image slider, we play with the margin-left property of sliderWrapper so that next image becomes part of slider visible area. We use animate method of jQuery which provides us the slide animation. And we set margin-left property to sliderWidth * (-curPos). So the value for image 2 would be -800, -1600 for third image, -2400 for fourth image and -3200 for last image. And again back to 0 for first image. And that would make images to rotate.

Here is complete jQuery code.

$(function() {
  var curPos = 0;
  var slider = $('.slider');
  var cntImages= slider.length;
  var sliderWidth = slider.width();
  $('#sliderWrapper').css('width', sliderWidth * cntImages);
  setInterval(SlideImage, 2000);

  function SlideImage() {
    if (curPos == cntImages - 1)
      curPos = 0;
    else
      curPos++;
     $('#sliderWrapper').animate({
      'marginLeft': sliderWidth * (-curPos)
    });
  }
});

What next?

This is a simple jQuery image slideshow with 5 images and you can add more images. All you need to do is to just add image tag. You can also modify the jQuery code as per your requirement and control the speed of image rotation via setting a higher delay for setInterval method.