Tag – Jquery

Blog

  • posted by mark
  • on Feb. 26, 2015
Something that's come up a lot in recent jobs is the need for a basic component to enable inline editing on certain fields inside webpages. This drove me to write a small, reusable JQuery component to do the trick, which I've made available on Github in case anyone else finds it useful. You can grab the code here - https://github.com/mtskelton/jquery-inline-editor - along with some basic usage instructions.
  • posted by mark
  • on Dec. 12, 2013
A scenario cropped up recently where I was developing a portable extension module in PHP, designed to be used as a drop in component on various sites, and I came across an issue I've hit a few times before. The problem is, the extension I was developing relied heavily on JQuery, but we couldn't guarantee that JQuery was installed in every site the extension would be used on. Sure, there's a couple of easy ways around this. We could have simply brought up a warning message, stating that JQuery was required for use with this plugin and requiring the site owner to install it in their theme. Alternatively we could have just included JQuery in the extensions headers, but this would have had the potential to overwrite any already included version, and as anyone who has ever dealt with JQuery version conflicts between other components supporting different versions knows .. that can be one massive headache. So the solution was to first check if JQuery is included, and load it if it isn't. This was achieved with the following code snippet, used in conjunction with a previous code snippet I've posted to dynamically load scripts .. which can be obtained here - Dynamically Loading Javascript After a Page Load.
function onJQInit() {
    alert("Loaded JQuery!");
}

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded .. load it
    loadScript("http://code.jquery.com/jquery-1.10.1.min.js", function() {
        setTimeout(function() {
            if(typeof jQuery != 'undefined')
                onJQInit();
        }, 100);
    });
} else {
    onJQInit();
}
If you need a later version of JQuery or want to use your own hosted version, just change the URL when calling the loadScript function. Also it's worth remembering if you want to do this as soon as possible, you'll need to wait until after the page has loaded before executing the loadScript function ... otherwise document.body may not exist. Again, there's an example for this you can adapt at Dynamically Loading Javascript After a Page Load.
  • posted by mark
  • on Dec. 12, 2013
I find this requirement is coming up increasingly more often, particularly as various website analysis tools recommend deferring the loading of Javascript elements until after the initial page load and insist on it when testing for mobile devices. So here's a handy little snippet I threw together to do just that. Firstly we need a pure JS function to load a script. This is done by creating a new script element and attaching it at the bottom of the body element. Here's the function:
function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
    
    document.body.appendChild(scr);		
}
You can use this function to load a script and execute a callback as soon as it's loaded ... like so:
loadScript('http://code.jquery.com/jquery-1.10.1.min.js', function() {
    alert('I loaded JQuery!');
});
And the bit of code below can be used to load multiple Javascript files, one after the other, once the page has finished loading.
var downloadJsAtOnload_j = 0;
var jsToDownload = ["script1.js", "script2.js"];
function downloadJSAtOnload(e) {
    if(downloadJsAtOnload_j < jsToDownload.length) {
        loadScript(jsToDownload[downloadJsAtOnload_j], function() {
            downloadJsAtOnload_j++;
            downloadJSAtOnload(e);
        });
    } else {
	// All scripts downloaded
    }
}

if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
Simply modify the jsToDownload array with your own scripts. Let me know how this code works for you, interested in any feedback!
  • posted by mark
  • on Sept. 7, 2012
Every modern web application gets busy from time to time, whether it be with background AJAX calls or simply just generating an unusually complex page, and you need to let your users know that it's doing something. A good way of doing this is to display an animated loader with a faded background to disable the busy area. Depending on what's loading you might want to do this over your entire page, or you might just want to fade out a single component or small area. There's a few plugins out there to do this for you automatically, but if you're using JQuery on your site (and if you're not, why not?), here's a few snippets to help you to roll your own in a matter of minutes.

Step 1 - The Loader Image

Firstly you need to obtain an animated loader image to use. Fortunately there's a bunch of websites out there that will generate one for you. Here's two I use: www.preloaders.net www.ajaxload.info Generate an image (ideally an animated gif) and save it somewhere.

Step 2 - The Stylesheet

Add the following elements to your site's stylesheet:
#ajax-loader { position: absolute; z-index: 1000; background: #fff url('ajax-loader.gif') no-repeat center; opacity: 0.75; display: none;}
Make sure to replace ajax-loader.gif with the filename and location of your loader image. And add the following to your site's main template (or on each page you want to use the loader)
<div id='ajax-loader'></div>

Step 3 - The Javascript

Add this function somewhere in your site's Javascript:
$.fn.showLoader = function() { pos = $(this).offset(); $loader = $('#ajax-loader'); if(pos !== undefined) { $loader.css('position','absolute'); $loader.css('top',''); $loader.offset(pos); } else { $loader.css('position','fixed'); $loader.css('top','0'); } $loader.width($(this).width()); $loader.height($(this).height()); $loader.fadeIn(); } $.hideLoader = function() { $loader = $('#ajax-loader'); $loader.fadeOut(); }
You can now show and hide the loader using the .showLoader() and .hideLoader() functions respectively. For instance, you can show the loader over the entire page using:
$(window).showLoader();
Or over a single element:
$('#element').showLoader();
You can hide the loader with just:
$.hideLoader();
And there you have it, it's probably not the most elegant solution and at the time of writing this has only been tested on Firefox and Chrome so I make no guarantees it's completely bug free. Feel free to use this snippet on any of your sites, and all suggestions, feedback and improvements are welcome.

Back