Change the URL with JavaScript without redirecting

If you have a part of your website that need to change the URL in the browser without having to refresh the whole page, than you shouldn’t use the window.location.href because this one will redirect into that page. window.location contains 2 others method that can do the job for you. The first one is assign. window.location.assign(url) is a method that will change the url and set in your history the new url. Sometime, we want to browser to change but not the history. A second method does that job — it’s called replace.

On the other hand, doing that mean that the user can navigate directly into your webpage by the url in the browser. If you changed the URL by just changing a hash tag that define a specific action in your website, you may have that action trigged by the click event but not when the user access the webpage directly from the url.

For example, you have several link for action like “open item1” and “open item2”. You change the url with window.location.assign because you want the user to be able to use the back button — use the history. So the history looks like this:

  • http://yourwebsite.com/page1
  • http://yourwebsite.com/page1#item1
  • http://yourwebsite.com/page1#item2

If someone go directly to the item2 than you need to execute the code behind this hash tag. To have your code executed you need to use the window event called onhashchange.

    window.onhashchange = function() {
        //Get the hash value from the url and execute your code       
    };

The onhashchange become a hub if all time the url change which can be convenient to have a central place has a content controller. This method removes the need to have action handled in every click that has hash url to just have the click event of these links to change the url and let the onhashchange handles which action to execute.

Here is an example:

<a id="report">Current Order Report</a>
<a id="edit">Edit Current Order</a>
$('#report').click(function(){
    window.location.assign("#open-current-report");
});

$('#edit').click(function(){
    window.location.assign("#edit-order");
});

window.onhashchange = function(){
    if(window.location.hash) {
        var hashFragment = window.location.hash.substring(1); // Get hash value (without #)
        switch(hashFragment) {
            case "open-current-report":
                //Do your action
                break;
            case "edit-order":
                //Do your action
                break;
        }  
  }
};

This example use JQuery to attach the click event but this is not required for the location assign, neither for the onhashchange — they are both pure JavaScript method and event.

How to create a bottom-right fixed button in CSS with expanding hover animation

If you need to have a button with minimal information and when the user hovers this one give more input before executing the action, here is something interesting. The code illustrates a use case that the button is fixed to the browser at the bottom-right of the screen but this kind of button can be used everywhere. The main purpose is to have a rich user experience with pro-active feedback in a minimal way. The initial state of the button is just a single icon.

PlusImage
Expected rendering

For that example, I haven’t use a glyph icon, neither an image, just a single plus character. This could be replaced with what ever you want. The idea is that when the user hover the icon that we have a transition to a bigger button.

Here is the button’s Html. The container is not required and is just there for the purpose of having this button sticky at the bottom-right of the window. The button element is the real button. This one will grows when hovering. It contains two texts: one when collapsed and one when extended.

<div class="right-corder-container">     
	<button class="right-corder-container-button">         
		<span class="short-text">+</span>         
		<span class="long-text">Add Me</span>     
	</button> 
</div>

The css does 90% of the job. The remaining 10% is that we need to have a hover JavaScript to add and remove a class to add the long text visibility. The first CSS style is about fixing the container at the bottom-right of the browser’s window.

.right-corder-container {     
    position:fixed;     
    right:20px;     
    bottom:20px; 
}

The next CSS style is what round up the button into a perfect circle. This is also where we setup the transition effect timing.

.right-corder-container .right-corder-container-button {     
     height: 62px;     
     width: 62px;     
     border:none;    
     background-color:#6FB583;     
     border-radius: 62px;        /*Transform the square into rectangle, sync that value with the width/height*/     
     transition: all 300ms;      /*Animation to close the button (circle)*/     box-shadow:2px 2px 5px rgb(25, 73, 15);     
     cursor:pointer; 
}

The span specify the plus sign to be placed in the middle. We use absolute position to have fined precision about where to place the text. Also, this is easier to ensure that even during the effect that this one remains at the same place.

.right-corder-container .right-corder-container-button span {     
    font-size: 72px;     
    color:white;     
    position: absolute;    
    left: 10px;     
    top: 16px;     
    line-height: 28px; 
}

The hover is where we specify the size of the final stage of the button. We also change the right side to be less round. This way, the button appears to be less than an oval, more to a label.

.right-corder-container .right-corder-container-button:hover {     
    transition: all 400ms cubic-bezier(.62,.1,.5,1);     
    width:200px;     
    border-top-right-radius: 5px;     
    border-bottom-right-radius: 5px; 
}

The next style block is about the long text effect. We want this text to appear slowly. We need to tweak some properties to be sure that the vertical scroll-bar does not get affected.

/*     Long text appears slowly with an animation. That code prepare the animation by hidding the text.     The use of display is not there because it does not work well with CSS3 animation. */ 
.right-corder-container .right-corder-container-button .long-text {     transition: opacity 1000ms; /*Only the text fadein/fadeout is animated*/     
opacity:0;                /*By default we do not display the text, we want the text to fade in*/     
color:white;     
white-space: nowrap;     
font-size: 0;             /*Set to 0 to not have overflow on the right of the browser*/     
width: 0;                 /*Set to 0 to not have overflow on the right of the browser*/     
margin:0;                 /*Set to 0 to not have overflow on the right of the browser*/ }


This is how we show the long text. We need to add a delay in the transition opacity because we do not want to start showing the text too early. Mostly because the container size is animated and not big enough to receive the text yet.

 /*     Animation to have a text that appear progressively. We need to play with a delay     on the width and the font-size to not have the browser have the text appears on the right     side of the browser view port. This has the side-effect of having an horizontal bar. */ 
.right-corder-container .right-corder-container-button .long-text.show-long-text{   
    transition: opacity 700ms,               
    width 1ms linear 270ms,       /*two thirds of the animation on the container width*/               
    font-size 1ms linear 270ms;   /*two thirds of the animation on the container width*/   
    opacity:1;   
    margin-top: 2px;                          /*Center the position vertically*/   
     margin-left: 65px;                        /*Center between the + and the right end side*/   
    font-size: 20px;                          /*Text size, cannot be defined initially without moving the scrollbar*/   
    width: auto;                              /*Required to be set with a delay (see animation) to not have scrollbar. Delay is to wait container to size up*/ 
}


The JavaScript is minimal and you do not have to use JQuery for a simple task as this. However, I had this one already available to here is the code with JQuery.

$(".right-corder-container-button").hover(function() 
{     
$(".long-text").addClass("show-long-text"); }, function () {     $(".long-text").removeClass("show-long-text"); 
});

This code is available in JSFiddle.

How to unit test private method

This is something that I got asked from little start-up up to Microsoft. How to you test private method? I often see horrible things. For example, if your class as 1 public method that call 5 privates method and you want to unit test 1 of the 5 methods, calling the public method to do so is wrong. Something can change anywhere in the class and break that test. Also, creating test this way is painful because it takes time to setup all variables to value that make all others method not fail. Once you reach the method you want to test you can start really testing what you are there for. An other horrible thing is to start using advanced shimming stuff that rely on reflection. The solution is simple : create more cohesive classes.

I think an example is better before continuing about how to divide code to help creating more efficient unit test. Here is a snippet that illustrate many problem. We have an Order class that has a list of item that can be bought. At some point, we want to pass a transaction so we have a method called Purchase which return the list of item that we can really purchase based on different business logic. For example, we allows only item that is between 0$ and 100$ to be bought, only item that is not discontinued, we can only buy 1 item of any kind per transaction, not more than 3 items at the same time can be in the basket and finally nothing above an order of 50$ is allowed (so we only add item to be purchase under 50$).

public class ShoppingBasket
{
    public List<Item> Items { get; set; }

    public List<Item> Purchase()
    {
        var canBeBought = new List<Item>();
        foreach (var item in Items)
        {
            bool canBuy = true;
            if (item.Money < 0 || item.Money > 100)
            {
                canBuy = false;
            }

            if (item.IsDiscontinued)
            {
                canBuy = false;
            }

            if (!this.IsUnique(item.Id))
            {
                canBuy = false;
            }

            if (this.IsShoppingBasketFull())
            {
                canBuy = false;
            }

            if (this.HasReachMaximumAmountPerOrder(canBeBought))
            {
                canBuy = false;

            }
            if (canBuy)
            {
                canBeBought.Add(item);
            }
        }
        return canBeBought;
    }

    private bool IsUnique(int id)
    {
        return this.Items.Count(d => d.Id == id) > 1;
    }

    private bool IsShoppingBasketFull()
    {
        return this.Items.Count >= 5;
    }

    private bool HasReachMaximumAmountPerOrder(List<Item> canBeBought)
    {
        return canBeBought.Sum(d=>d.Money) > 50;
    }
}

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }
}

If you want to test if the Lambda expression is well formed for the IsUnique method, you will have to create a list of items and pass it to the ShoppingBasket class. So far, this is fine. However, you cannot call the method IsUnique because this one is private. You have two choices. You break the encapsulation of the ShoppingBasket by changing the visibility from private to public or you refactor your class to something more testable, more cohesive and more object oriented. Changing the encapsulation is fine. In fact, in that case it does not really matter because it does not disrupt the system. Someone could call IsUnique any time and it does not change any operational flow. However, is it really the responsability of the ShoppingBasket to handle the unique?

Let’s start trying to unit test this actual code to illustrate how it is not a good idea to test through the public method to reach a private method.

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasNotUniqueItem()
{
    // Arrange
    var shoppingBasket = new ShoppingBasket();
    var item1 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    var item2 = new Item() {Id = 2, IsDiscontinued = false, Money = 10};
    var item3 = new Item() {Id = 3, IsDiscontinued = false, Money = 50};
    var item4 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    shoppingBasket.Items = new List<Item> {item1, item2, item3, item4};

    // Act
    var itemThatWeCanPurchase = shoppingBasket.Purchase();

    // Assert
    Assert.AreEqual(2, itemThatWeCanPurchase.Count);
}

You will tell me that this is fine. In fact, it is. In that case the problem is not the amount of preparation. It is often the case, but not that time. The problem is that if tomorrow the threshold of 50$ go down to 10$ that this unit test will fail. Right now, the item id 2 and 3 are returned but if this limit goes from 50$ to 10$ than the id 2 is out which will return only one item. The unit test about unique fail because of the maximum amount per order. This is wrong.

A unit test must test a unit. It has to test a single thing. It has to be atomic. This is why we need to refactor that code.

The first thing to do is to ask who is the expert of the field for each logic. The first logic concern the logic about that we can only buy item with money between 0$ and 100$. This raise multiple questions.

  1. Is it a shopping basket logic?
  2. Does that logic is universal on the software we are building or just for specific case? Does this range may change during the lifetime of this software?
  3. Do we have different kind of Item?

The first question make sense. Maybe depending of the type of shopping basket that logic can change. For example you could have “SmallShoppingBasket” and a “BigShoppingBasket” and depending of the basket the threshold change. This is why we cannot build a software without knowing the specification: the code changes depending of what are the rules. Creating a generic system for all case increase the time to build this one by a huge magnitude of time. That said, for that first condition, we need to extract that code out of the loop in all case. The reason is that this condition is independent of all items — it is a condition on a single item. Since we are not planning to have multiple basket and the amount belong to an item, for that use case, it makes sense to set the condition inside the Item class. This change result having one more method in Item and the unit test to call that method.

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }

    public bool IsPriceLegitForPurchase()
    {
        return this.Money < 0 || this.Money > 100;
    }
}

The second condition is checking if the item is discontinued. The call is already on the item which is great. However, already have a condition on the item done one line above since our last refactoring on the price.

foreach (var item in Items)
{
    bool canBuy = true;
    if (!item.IsPriceLegitForPurchase())
    {
        canBuy = false;
    }

    if (item.IsDiscontinued)
    {
        canBuy = false;
    }
    // ...

Instead of calling twice the item we should think. These two operations has something in common: it validates the item for purchase. We should have a method in the item that does that for us. Not only it will self-document what it is going on but that logic could be reused later without having to duplicate both calls. We end up having a single validation method for purchase in item.

public bool IsValidForPurchase()
{
        if (!this.IsPriceLegitForPurchase())
        {
            return false;
        }

        if (this.IsDiscontinued)
        {
            return false;
        }
    return true;
}

The test is also clearer.

//...
if(!item.IsValidForPurchase())
{
   canBuy = false;
}
//...

The third condition was to check if the shopping basket is full. The logic belong to the basket because this one is the one who know its size, which is 5. The problem is that when we will test that logic, we do not want to have to create items that necessary pass condition for “IsValidForPurchase” method. We just want to create a list of item and test the count. That said, this is a perfect case that this method should be public.

The next condition is about if the list of item that is valid to purchase has still some place to add additional item. This is an interesting case. This logic does not belong to item, it belongs to the list. It means that this list is an entity which some properties, states, etc.

public class ItemValidToPurchase : List<Item>
{
    public bool HasReachMaximumAmountPerOrder()
    {
        return this.Sum(d => d.Money) > 50;
    }
}

The condition in the Shopping Basket is just to call the method.

if (canBeBought.HasReachMaximumAmountPerOrder())
{
    canBuy = false;
}

So the final code looks like this for the test about unique.


private ShoppingBasket GetShoppingBasket()
{
    var shoppingBasket = new ShoppingBasket();
    var item1 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    var item2 = new Item() {Id = 2, IsDiscontinued = false, Money = 10};
    var item3 = new Item() {Id = 3, IsDiscontinued = false, Money = 20};
    var item4 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    shoppingBasket.Items = new List<Item> {item1, item2, item3, item4};
    return shoppingBasket;
}

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasNotUniqueItem()
{
    // Arrange
            var shoppingBasket = this.GetShoppingBasket();

    // Act
    var isUnique = shoppingBasket.IsUnique(1);

    // Assert
    Assert.IsFalse(isUnique);
}

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasUniqueItem()
{
    // Arrange
    var shoppingBasket = this.GetShoppingBasket();

    // Act
    var isUnique = shoppingBasket.IsUnique(2);

    // Assert
    Assert.IsTrue(isUnique);
}

And the classes code look.

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }

    public bool IsPriceLegitForPurchase()
    {
        return this.Money < 0 || this.Money > 100;
    }

    public bool IsValidForPurchase()
    {
            if (!this.IsPriceLegitForPurchase())
            {
                return false;
            }

            if (this.IsDiscontinued)
            {
                return false;
            }
        return true;
    }
}
public class ItemValidToPurchase : List<Item>
{
    public bool HasReachMaximumAmountPerOrder()
    {
        return this.Sum(d => d.Money) > 50;
    }
}
public class ShoppingBasket
{
    public List<Item> Items { get; set; }

    public ItemValidToPurchase Purchase()
    {
        var canBeBought = new ItemValidToPurchase();
        foreach (var item in Items)
        {
            bool canBuy = true;
            if(!item.IsValidForPurchase())
            {
                canBuy = false;
            }

            if (!this.IsUnique(item.Id))
            {
                canBuy = false;
            }

            if (this.IsShoppingBasketFull())
            {
                canBuy = false;
            }

            if (canBeBought.HasReachMaximumAmountPerOrder())
            {
                canBuy = false;
            }

            if (canBuy)
            {
                canBeBought.Add(item);
            }
        }
        return canBeBought;
    }

    public bool IsUnique(int id)
    {
        return this.Items.Count(d => d.Id == id) == 1;
    }

    public bool IsShoppingBasketFull()
    {
        return this.Items.Count >= 5;
    }
}

As you can see, the condition has changed on the IsUnique method. Because and error was present and only could have been detected with a valid set of unit test on that method. We could go even further by refactoring even more this code. I’ll write a second post about what we could have done with a more flexible code that allow to have dynamic validation using other design pattern.

You can find the initial code and the final code in this Git Repository.

Quick Add Html Button with CSS3 and JQuery

This is a small JavaScript and CSS control that allows to have some edition from a textbox in a fashion that this one is only a button to minimize space and once clicked become a more extended version. The goal is to have a way to add information in a quick way without taking too much space. This is perfect for situation where adding information is not the main task. The use case is that a user want to add information which require a text box. The user click the button to open the edition which reveal a text box. The button does not need to stay there because we want to save space so the button transforms into a closing button which cancel the operation if required. When the user starts to type, a save button is added. From there, the user can click the cancel button or hit save. In both case, the text box is rolling back and the user interface come back to the initial state. This design is intended to be minimal. There is not label. This is why we need to use a watermark, also known as placeholder in the text box. Since we want to limit button, the expand button and cancel (collapse) button is the same. To make sure that the user knows what the button is doing we display a tooltip but also we have an animation that transform visually the button to its intend.

To keep it simples, let’s start with a division that will hold all our Html elements.

<div id="container">
</div>

Next, we need to create our three main controls. The first one is the input where the user will write any information that will be saved. The second one is the toggle button that expand or collapse the input box and the third one is the save button that will be displayed only when the user save.

var $controlContainer = $('#container');

var $inputBox = $("<input>")
	.attr('id', 'inline-editor-textbox')
        .attr('type', 'text')
	.attr('value', '')
	.attr('maxlength', 20 )
	.attr('style', 'display:none')
	.attr('placeholder', "This is some watermark")
	.addClass('hide-input-inline')
	;
$inputBox.appendTo($controlContainer);

var $buttonToggle = $("<button>")
	.attr('id', 'toggleButton')
	.attr('title', 'Open')
	.attr('type', 'button');
var $spanIcon = $('<span>')
	.addClass("glyphicon glyphicon-plus");
$spanIcon.appendTo($buttonToggle);
$buttonToggle.appendTo($controlContainer);

var $buttonOk = $("<button>")
	.attr('id', 'okButton')
	.attr('style', 'display:none')
	.attr('title', 'Ok')
	.addClass('hide-ok-button')
	.attr('type', 'button');
var $spanIconOk = $('<span>')
	.addClass("glyphicon glyphicon-save");
$spanIconOk.appendTo($buttonOk);
$buttonOk.appendTo($controlContainer);

The next step is to add events. The toggle will open and close the input. It will also change the icon of the button from a “+” to a “x”. The okay button will save the information and collapse the input if everything is fine. The keyup is there to show the save button if the text box contains text.

$buttonToggle.click({ input: $inputBox, buttonToggle: $buttonToggle, buttonOk: $buttonOk},onToggle);
$buttonOk.click({ input: $inputBox, buttonToggle: $buttonToggle, buttonOk: $buttonOk},onOk);
$inputBox.keyup( { input: $inputBox, buttonOk: $buttonOk }, onKeyUp);

The toggle function has reference to some of our controls. This is a great way to pass reference without having to communicate through JQuery selector. Depending of the state of the toggle, which is the class “hide-input-inline” we make it appears or not. We add a delay because we have CSS3 animation and we want everything to be smooth together.

function onToggle(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonToggle = data.buttonToggle;
	var $buttonOk = data.buttonOk;

	var isHidden = $input.hasClass("hide-input-inline");
	if (isHidden) {
		$input.fadeIn();                            
		$input.removeClass("hide-input-inline");    
		$input.addClass("show-input-inline");       
		$input.val('');                             
		$buttonToggle.addClass("add-to-close");     
		$buttonToggle.attr('title', 'Close');
	}
	else {
		$input.removeClass("show-input-inline");   
		$input.addClass("hide-input-inline")      
			.delay(600)
			.fadeOut();                             
		$buttonToggle.removeClass("add-to-close");  
		$buttonOk.addClass("hide-ok-button");     
		$buttonOk.removeClass("show-ok-button")
			.delay(600)
			.fadeOut();                             
		$buttonToggle.attr('title', 'Open');
	}
}

The key up is to check the length but we could also check for “Enter” to be pressed and invoke the Ok code. The code is adding or removing classes, with a delay to let CSS animation to be executed.

function onKeyUp(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonOk = data.buttonOk;
	if ($input.val().length === 0) {
		$buttonOk.removeClass("show-ok-button");
		$buttonOk.addClass("hide-ok-button")
			.delay(600)
			.fadeOut(); 
		htmlElementWithIconState($buttonOk, true);
	} else {
		$buttonOk.fadeIn();
		$buttonOk.addClass("show-ok-button");
		$buttonOk.removeClass("hide-ok-button");
		htmlElementWithIconState($buttonOk, false);
	}
}

This helper method is used to mark the save icon into a disable state. At this moment, this is not really used but if validation is added we could still have the button add without having to remove it until the user fix the problem.

	
function htmlElementWithIconState($element, disabled) {
    $element.prop("disabled", disabled);
    $element.find('.glyphicon').css('opacity', (disabled === true) ? .4 : 1);	
}

Finally, we have the okay button hit which close up the text box and every buttons. In real life, a callback into a real save or okay code would be executed. If successful than close, otherwise keep everything open for the user to adjust his or her input.

	
function onOk(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonOk = data.buttonOk;
	
	onToggle(jqueryEvent);
}
#toggleButton,
#okButton
 {
    padding:0 2px 4px 2px;         
    margin-left:3px;               
    height: 22px;                  
    width: 22px;                   
    vertical-align: top;           
}


#toggleButton span.glyphicon
{
    transition: all 1000ms ease;
}


#okButton {
    transition: all 1000ms ease;
}


.hide-input-inline {
    width:0;
    transition: width 1000ms ease-in-out;
}


.show-input-inline {
    width:210px;
    transition: width 1000ms ease-in-out;
}


.add-to-close span {
    transform: rotate(135deg);
}


.hide-ok-button {
    opacity:0;

}


.show-ok-button {
    opacity:1;
}

	
#inline-editor-textbox::-webkit-input-placeholder { /* WebKit browsers */
    color:#7f7f7f

}
#inline-editor-textbox {
    border: none;
    background-color: #E2E2E2;
    color:#7f7f7f;
    padding-left:4px;
    height:22px;/*To fix the size of the button since we do not have any border*/
}

#inline-editor-textbox:focus {
    outline: none; 
    background-color:white; 
}