Archive for the ‘jQuery’ Category

oliverm

The Gist of Code Sharing

Wednesday, April 17th, 2013

Agile development teams often need to share code while in the heat of battle.

At the high end of the scale, there are publicly-accessible repositories, such as GitHub. Creating a GitHub project is obviously overkill for those wishing to simply pass a few key lines of code to their buddy in the next seat.

For stand-alone, runnable demo code, sites like Plunker and JSFiddle  are great. You will see references to these sites wherever HTML, CSS and JavaScript bugs are reported; for example stackoverflow and the AngularJS Google Group.

But again, maybe overkill for just a few lines.

So what are the other options for code sharing?

  • Email – I suppose, but there may be delays in receiving the email if your server is slow.
  • Skype or other messaging service – Alright, but you lose history eventually.
  • USB Key (sneaker-net) – It works, but it is hard to share it with a lot of people and history is also an issue.
  • Gist – This has been around a couple of years but I’ve only just discovered it since it is baked into IntelliJ/WebStorm. Gist is a GitHub sub-project and is associated with your GitHub account. For example, my GitHub account is at https://github.com/oliverm2112 and my Gists are at https://gist.github.com/oliverm2112. Gist allows developers to post snippets of code in various languages and features in-place editing and syntax highlighting.

Here is a Gist home page and a code sample:

 

 

 

 

Here is a shot of IntelliJ/WebStorm’s abilitity to create a Gist from within the IDE:

Hopefully you will find this a useful way to share information.

Chad Upton

Adding an X to Close a noty.js Notification

Monday, February 4th, 2013

By Chad Upton – senior consultant

Noty is a jQuery plugin for doing popup notifications in a browser. They’re simple, pretty, and they slide in like toast style notifications on the desktop.

They can be positioned at the top, side, bottom or even in a custom container. Here’s a screen capture of one that slides in from the top:

Noty does have a built in way to do confirmation buttons, but it adds an additional line to the popup, which isn’t as clean as the example above. Here’s what the built in method looks like:

I think it looks a lot cleaner with just the “x” to close. My example just shows one button (the “x”) but you modify my example and put “ok” and “cancel” buttons where I have the “x” if you need more than just close functionality.

Adding custom html to noty is very easy, and my example also includes a callback to handle a user click on the “x” (or your substitute buttons).

Source Code:

You can run and view the working source code on jsfiddle here and an explanation of the code follows:

1. I’ve added some css to float the div containing the button (“x”) to the right:

<style>
.notyCloseButton {
position: relative;
float: right;
}
</style>

2. Import the necessary javascript files for jQuery and noty. These can be found in the side panel of jsfiddle, but should be added above the existing script tag in the document if you copy the code from jsfiddle and try it elsewhere:

<script src="lib/jquery-1.7.2.min.js"></script>
<script src="lib/noty/jquery.noty.js"></script>
<script src="lib/noty/layouts/top.js"></script>
<script src="lib/noty/themes/default.js"></script>

3. On document ready, create the noty notification:

var n = noty({
type : 'warning',
text : '
<div>This is a notification<img id="notyCloseButton" class="notyCloseButton" src="http://www.newyyz.com/ntgsite/wp/wp-content/uploads/2013/02/x.png" alt="" /></div>
'
,
layout : 'top',
dismissQueue : true,
callback : {
afterShow : function () {
$('#notyCloseButton').one('click', function() {
alert("You closed the noty");
});
}
},
timeout : 5000
});

You’ll notice I’ve added an id to the img tag (notyCloseButton) and then added a click event listener to that tag so you have a callback to execute code if the user closes the noty. If you don’t need to respond to the user closing the noty, then you can leave this out of course.

Hopefully that helps you make cleaner notifications with a close (or other) buttons.

If you need help specific to your application, contact us for consulting on your project.

Chad Upton

Animating CSS Properties with jQuery

Thursday, August 2nd, 2012

By Chad Upton - senior consultant

jQuery is a seemingly endless tool for making advanced tasks easy and cross browser compatible. One of those tasks is animation, and jQuery is great at it.

For example, lets say we’re building a shopping cart application and we’d like to grow and shrink a product image when a user clicks on it. Here’s the HTML tag for the image:

<img id='logo' src='logo.gif'/>

In JavaScript, we’ll target the image with jQuery syntax:

$('#logo')

Next, we’ll add a toggle event handler. Toggle on its own will simply show/hide something, but we can add extra handlers for more advanced functionality. Here, we’ll add two methods that will be called alternatly each time the logo is clicked

$('#logo').toggle(function() {
}, function() {
});

Inside each of those functions, we’ll specify the property we want to animate. In this case, we’ll use the image’s height. We want it to grow by 100 pixels and we want that animation to take approximately 400 milliseconds to complete. The alternate function will shrink the image by 100 pixels over 400 milliseconds.

$(document).ready(function(){
$('#logo').toggle(function() {
$(this).animate( {height:'+=100px'}, 400, 'swing');
}, function() {
$(this).animate( {height:'-=100px'}, 400, 'linear');
});
});

I’ve also added “swing” and “linear” easing to these animations. If you’re not familiar with easing, it can make animations look more fluid by changing the acceleration of the animation at the beginning and the end. Linear easing offers no change in acceleration while swing offers a slight change. The difference is subtle, but you can see it if you look closely.

I published the working code to jsfiddle, click here to try it out.

 

 

oliverm

Going Loopy for Closures

Monday, June 18th, 2012

We do a lot of jQuery DOM manipulation in our projects here at New Toronto Group. Often we are required to create applications with UIs that are generated on-the-fly, based on various runtime conditions.

One problem we see often is when we want to attach an event listener on a dynamically-created object, such as  a button, and maintain a reference to that button’s index while it was created.

Sounds simple enough. Most developers would begin by coding something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.initBroken = function () {
    var times = 5,
        i;

    for (i = 0; i < times; i += 1) {
        var button = $('<button>I\'m button '
            + i
            + '</button><br/>');

        $('body').append(button);

        button.on('click', function (i) {
            alert(i);
        });
    }
};

So what happens when you click one of the buttons? That’s right – it alerts 5 every time. The alert function uses the i variable as it is when the button is clicked. Because the for loop completed when the button was clicked, i is 5. Dang…

 

So how do we capture the value of i at the time the button was created? This is where closures come in. We can leverage the fact that JavaScript functions each have their own scope. While we’re looping and creating the button, we can create a function which holds this value of i, and then returns it when the button is clicked. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
app.initFixed = function () {
    var times = 5,
        i;

    for (i = 0; i < times; i += 1) {

        var button = $('<button>I\'m button '
            + i
            + '</button>
'
);

        $('body').append(button);

        button.on('click',
            function (j) {
                return function () {
                    alert(j);
                };
            }(i)
        );
    }
};

On line 15, we’re constructing a new function to return. Notice that we’re sending the function the value of i on line 18 when it is being created. It is this value that the function retains and returns when the button is clicked. (You may need to stare down this code for a few minutes before it sinks in.)

You can go one step further and move the inner function outside the for loop. This technique is illustrated in Douglas Crockford’s JavaScript: The Good Parts which inspired the solution presented here.

 

 

 

oliverm

Links roundup

Friday, November 4th, 2011

Here are a few unrelated links I’d like to pass on for your reading pleasure.

  1. Opportunistic Refactoring by Martin Fowler, author of the best programming book ever (Refactoring).  I’ve been preaching this one for a long time: “while you’re in there, refactor any smelly code, but don’t get caught in a death spiral”.
    http://martinfowler.com/bliki/OpportunisticRefactoring.html 

  2. jQuery4u – lots of great jQuery plug-in round-ups. I’m starting to visit this almost daily now.
    http://www.jquery4u.com/ 

  3. Finally, for you old KDE 3 fans, the beast is still alive and well. I loaded this onto a VM and started feeling very sentimental for the old days when KDE didn’t suck and I didn’t have to settle for Gnome.
    http://www.osnews.com/story/25283/KDE_3_5_Fork_Trinity_Releases_Third_Major_Update 

As usual, I look forward to your comments on any of these.

Oliver