Tag Archives: jquery

Add Pattern Support for HTML5 Input Type Number with jQuery

Ran into an issue earlier today that I could not figure out and ended up asking my second question on StackOverflow in seven years.

I was trying to use <input type="number" pattern="[0-9]{8}"> to enforce 8-digit numbers while allowing leading zeros. This was being done on an optional field (no required attribute) and I could not understand why it was bypassing my pattern on the populated field (eg: value “1234” was accepted, pattern ignored).

Peter B. over at SO (kudos) pointed me to the MDN reference that provided the reason… number input does not support pattern attribute

By design! While their reasoning makes sense from a general perspective, the min/max attribute workaround does not help where leading zeros are acceptable (eg: min="00000001"is the same as min="1" for obvious reasons). Unfortunately I need all 8-digits for my purposes. I also tried using minlength and maxlength attributes as a hail-mary to no avail.

Here is a jQuery shim I wrote for my main script file thereby adding pattern support the <input type="number"> Continue reading Add Pattern Support for HTML5 Input Type Number with jQuery

How to Continue Using Buttons with “data-loading-text” in Bootstrap 4 with jQuery

While converting a Bootstrap 3 template design for use with Bootstrap 4, I noticed they removed stateful buttons (eg: “loading” and “reset” button states) from BS4! Granted it was mentioned in BS3, but I never noticed the deprecated warning 🙁

The deprecated code for showing a button’s loading state was $('#selector').button('loading') and to return the button to its original state you would use  $('#selector').button('reset') . Continue reading How to Continue Using Buttons with “data-loading-text” in Bootstrap 4 with jQuery

Add Mouse Wheel Support to Bootstrap Carousel with jQuery

I was adding mouse wheel events to a ul element with the CSS rule overflow:hidden to emulate mouse wheel scrolling when no scrollbar was present.

The links in the unordered list also trigger a Bootstrap 4.1 Modal that contains a Bootstrap Carousel. So I decided to add the same functionality to my modal carousel gallery. Continue reading Add Mouse Wheel Support to Bootstrap Carousel with jQuery

Toggle Password Display in HTML5 with jQuery

Do you have  a password field that the user wants to be able to view at the click of a button? Here is the solution I came up with to handle that need…

The field…

<div class="input-group">
  <input type="password" name="password" value="P@$$w0rD" placeholder="Password" id="input-password" class="form-control" required>
  <span id="view-password" class="input-group-addon"><i class="fa fa-eye" aria-hidden="true"></i></span>
</div>

The javascript… Continue reading Toggle Password Display in HTML5 with jQuery

Automatically expand textarea to fit content using jQuery without autogrow or autosize plugins

I’m sure there is a more efficient way to do this, but it suited my needs.

<script>
$(function() {
    $('textarea').keyup(function(){
        $(this).each(function(index, element) {
            $(element).height(element.scrollHeight);
        });
    }).keyup(); //trigger event to initialize pre-filled textareas
});
</script>

Enjoy 🙂

How-To: Reload verification image using Codeigniter 2 CAPTCHA helper

Out of the box, CodeIgniter has a good CAPTCHA helper to use in your web applications. Here is a simple example of how to get a new CAPTCHA image without having to reload the page 😉

Basic Controller

class Welcome extends CI_Controller {

    private $captcha_path = 'assets/img/captcha/';

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->helper(array('captcha'));
        $captcha = create_captcha(array(
            'word'        => strtoupper(substr(md5(time()), 0, 6)),
            'img_path'    => $this->captcha_path,
            'img_url'    => $this->captcha_path
        ));
        $data = array(
            'captcha'        => $captcha
        );
        $this->session->set_userdata('captcha', $captcha['word']);
        $this->load->view('welcome', $data);
    }

}

The View (jQuery used for UI buttons and altering CAPTCHA image ‘src’ attribute)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/blitzer/jquery-ui.css">
<script>
$(function(){
    $('#new_captcha').button({
        text: false,
        icons: {
            primary: 'ui-icon-refresh'
        }
    }).click(function(event){
        event.preventDefault();
        $(this).prev().attr('src', 'welcome/new_captcha?'+Math.random());
    });
});
</script>
<?php echo $captcha['image']; ?>
<a href="#" id="new_captcha">Reload CAPTCHA</a>

Modified Controller Continue reading How-To: Reload verification image using Codeigniter 2 CAPTCHA helper

jQuery UI replacement for javascript:confirm() links

Here is a nice confirmation handler to replace javascript:confim() links using jQuery UI…

$(function() {
    $('.ui-icon-trash').click(function(event){
        event.preventDefault();
        var targetUrl = $(this).attr('href');
        $('<div title="Confirmation Required"><p>Delete this record?</p></div>').dialog({
            autoOpen: true,
            modal: true,
            resizable: false,
            buttons: {
                Yes: function() {
                    window.location.href = targetUrl;
                },
                No: function() {
                    $(this).remove();
                }
            }
        });
    });
});

I use it for “delete” links (should be obvious) but it can be easily adjusted for any other type of confirmation.

Cheers!

IMPROVED: Open all external links in a new window using jQuery

In the original post I covered how to use jQuery to automatically make external links open in a new window. The method however was slightly flawed in my opinion since…

  1. It did not check form action attributes
  2. It assumed ANY link starting with “http[s]://” was external

Here is my new and improved method for making all external site links open in a new window. It now includes form tags, one less selector for secure and non-secure link urls, AND excludes any of those which link to an internal page where the full url may have been specified.

$('a[href*="://"], form[action*="://"]').not($('a[href*="://'+location.host+'"]')).attr('target','_blank');

A quick breakdown…

  1. a[href*=”://“] and form[action*=”://“] matches the elements where a full url has been specified
  2. .not($(‘a[href*=”://’+location.host+'”]’)) excludes all matched items that include the current host (eg: http://www.robertmullaney.com/)
  3. finally we update the target attribute of the the remaining links open in a new window

Why this is important:

Once you have a user on your site, the worst thing you can do is send them away. Also, you will easily annoy them if all links open in new windows and cause them to leave anyhow. This way, only the links that pull them away from site site are opened in new windows. When they are done on the external sites, they close the browser and there your site remains.

Calculate the total height of child elements of a clipped (overflow: hidden) parent tag

Ever have an element with clipped content and wanted to know the total height of the elements contained therein? I have a client who wants the height of the main content to be clipped to a preset height (don’t ask me why). Which means I need to dynamically add a “read more” link to expand the container and show all the content.

Well, here’s how you calculate the combined height of the children with jQuery… Continue reading Calculate the total height of child elements of a clipped (overflow: hidden) parent tag

My HTML5 base template (skeleton file) with jQuery from Google CDN

Below is the standard HTML5 template I start most of my projects with. It includes the latest 1.x version of jQuery, jQuery UI, and the desired jQuery UI theme. It also has a conditional comment that checks to see if the current browser older than IE9 and includes HTML5Shiv to make sure new elements are rendered properly in older IE browsers.

While I don’t claim this is the best skeleton HTML5 template, I think it is a very solid foundation to start from 😉

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css">
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script>
$(function() {
    //DOM is Ready
});
</script>
</head>
<body>

</body>
</html>

jQuery Add Bookmark to Favorites Script

Here is a quick example of how to use jQuery along with traditional browser sniffing techniques to create a dynamic “Bookmark Us” link.

Google CDN (latest 1.x version, theme)…

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link type="text/css" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/blitzer/jquery-ui.css" />

The javascript… Continue reading jQuery Add Bookmark to Favorites Script