ruler and graphboard

How to Animate an Auto-height Element

ruler and graphboard

Animating an auto-height element seems like it should be fairly straightforward, however it seems I’m not the only one who has struggled with this particular issue.  The problem is usually some variant of the following:

  • I have some element I would like to allow to vertically expand and collapse.
  • The element has dynamic content – so therefore the height of the expanded element is unknown/dynamic.
  • I need to set the height of the element to auto to allow the element to change height based on its contents.
  • CSS doesn’t allow transitioning to auto height so – it just jumps to the height when expanding/collapsing.  No animation 🙁

 

This is what I want to do.

Showing auto-height expander

Some Workarounds

You may find several potential solutions to this problem if you spend a bit of time poking around the internet.

For example – there is the max-height workaround.  In this solution you would basically transition the max-height attribute instead of the height. The trick is to set the final max-height to something way larger than you think the element will ever grow.  This will effectively animate to the height of the element’s contents.  This might feel a little hanky to you – and for good reason. For starters – you have to guess what might be the largest the contents of the will ever get. But the content is dynamic – so that could easily get out of hand. Furthermore, the transition will animate to the full max-height specified. The visible height will stop at the height of the content – but the transition thinks it needs to grow all the way to the max-height. So for example – if you set a transition time of 300ms – it will take that long to animate to the full max-height even though the visual height stops well before then.

Other workarounds involve hiding the visual elements instead of changing the actual height or using javascript to manually animate/hide elements etc., but these are even more complicated than the max-height solution and introduce a slew of new problems to deal with (the very least of which is wreaking havoc on the element’s accessibility).

My Hack Solution

If you’re the kind of person that peeks at the end of the book (shame on you) then you can check out my working solution on codepen.

It still uses CSS to animate the height property through the transition property.  However it also uses a bit of JavaScript to store some state for the element.

This solution will not work for all situations – but it suited my needs well, but there are some restrictions:

  • You must know the initial default height of the element.  This means if you don’t know what content will be in your div on initial load – this might not work so well.  But if your element has an initial set of known contents this should work like a champ.
  • Content can only be added or removed from the element while it is in the expanded state.  If content is added/removed from the div while collapsed  – then you’re out of luck again.

Assuming your needs fulfill these requirements – this should work nicely.

The solution essentially works like this:

  1. Store the initial height of the element in a variable somewhere. We’ll call it expandHeight for now.
  2. When the element expands – you can easily transition the height from 0 to the expandHeight.
  3. After the transition is complete (use a setTimeout based on whatever you set the transition-duration property to) then set the element’s height property to auto
  4. Add/remove content to the element as desired
  5. When collapsing –
    1. First store the element’s current height back into the expandHeight variable.
    2. Next set the element’s height back to a fixed value (what you just stored in expandHeight). This is because the element cannot transition from an auto height either. It can only transition to/from a fixed height.
    3. Now you can transition back to a height of 0.
  6. When you need to expand again – just start at step 2 above and repeat as necessary!

 

That’s about all there is to it and it has worked well for me. One caveat is that you may need to stick step 5.3 in another setTimeout with a very small delay to allow the DOM time to register that the height attribute has changed from an auto height to a fixed height.

Here’s my fully functioning example:

See the Pen Auto-Height Expanding Div by Nate Gibbons (@marshallformula) on CodePen.

The astute observer might notice that it would not take too much imagination to create a high order ReactJS component out of this solution that stores its own state internally so you can re-use it anywhere with ease.

Let me know what you think.  More importantly – let me know if you’ve got something even better!  Cheers!

Feature Photo by Christian Kaindl
Package Your WebApp

Package Your WebApp

package webapp

package webapp

So you’re building modern web application. That most likely means you’re building a Single Page Application (SPA) in JavaScript and reading data from a server via REST. The REST server code could be implemented using any number of programming languages and technology stacks.

There are a few schools of thought when it comes to developing a web application. One option is to keep the development of client and server code completely separate. Another approach is to develop both client & server code together via Universal Javascript. Additionally there are issues regarding how to store the code base(s) in the repository, how versioning is applied, and finally how the code is deployed and maintained.

This article proposes a solution that has worked well for one of our projects at Volume Integration. I’ve created a sample application that demonstrates some of the key components of this solution.

You can download/clone the project here:

https://github.com/marshallformula/packaged-webapp

2015 Utah State Park Attendance Example Application

The sample application is a very simple web application that shows a graph of Utah State Park attendance for 2015. Here is a screenshot of the finished product.

Sample Web Application Screenshot

The main components of the application are:

Standalone Java Web Server (Spring Boot). The main purpose is to provide a set of REST services for the WebApp to consume. But it also initially serves the static web application code (HTML, CSS, JavaScript)

Web Application (SPA). The web application uses modern web application practices – including transpiling ES2016 code using Babel, packing and optimizing code and dependencies using webpack, as well as compiling advanced css using preprocessors like less and sass.

Requirements

Development of this application requires the following:

Developing the Application

This application is set up so that you can develop the REST services and JavaScript application independently.

Developing REST Services

The REST services are written in Java Utilizing Spring Boot & Spring MVC functionality. All of that code is located in src/main/java.

To develop the services code interactively just run

gradlew bootRun

This will start up the embedded webserver (Tomcat by default) and deliver your services. As you write your code – the server should detect code changes and restart as necessary due the inclusion of Spring Boot DevTools.

If you are developing/running the REST server interactively while developing the JavaScript web application – you will need to add a system property like so:

gradlew bootRun -Dcors.origins=http://localhost:3000

There is one hack feature that’s required to enable the bootRun gradle tasks to accept and apply configuration properties in this manner. Add this snippet to the build.gradle file:

1
2
3
4
bootRun {
systemProperties System.properties
}

This is because when developing the web application – it will be running on its own development server on port 3000 (see below) which will have a different host and we will need to configure CORS to allow the web application to consume the REST services.

I won’t delve into the all of the intricacies of how Spring MVC works its magic, but the following configurations are required in the app to make it work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@SpringBootApplication
public class ExampleApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args){
SpringApplication.run(ExampleApplication.class, args);
}
@Value(“${cors.origins}”)
private String origins;
//this is to add allow the CORS origins specified on the cors.orgins property to communicate with this server.
@Override
public void addCorsMappings(CorsRegistry registry) {
if(!StringUtils.isEmpty(origins)){
CorsRegistration registration = registry.addMapping(“/api/**”);
Arrays.stream(origins.split(“,”))
.map(String::trim)
.forEach(registration::allowedOrigins);
registration.allowedMethods(“GET”, “POST”, “PUT”, “DELETE”);
} else {
super.addCorsMappings(registry);
}
}
//this is necessary to forward all un-mapped requests to index.html.
//This is required if you want to use the HTML5 History API
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.setOrder(Ordered.LOWEST_PRECEDENCE);
registry.addViewController(“/**”).setViewName(“forward:/index.html”);
}
//this is helpful in connection with the method above to allow paths to the /assets folder for images, files etc
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/assets/**”).addResourceLocations(“classpath:/static/”);
super.addResourceHandlers(registry);
}
}

Developing the JavaScript Web Application

The JavaScript web application is set up to operate as a standalone web application (when provided some REST services to connect to). All of the web application code is under src/main/app. You will need to be in this directory to run the following commands.

The web application is packaged with webpack and utilizes webpack-dev-server to enable interactive development.

First you must download all of the necessary dependencies from npm.

npm run setup

Once that is complete you are ready to start the development server by simply running npm start. However the application can be configured via an environment variable to connect to a REST server at any location. This way you can work on the web application and connect to any instance of your API (dev/test environments).

If you would like to connect to your local instance of the REST services that are running using the instructions above – you will just need to set the REST_URL environment variable to http://localhost:8080/api. The easiest way to do that is to just prepend the variable declaration to the start command like this:

REST_URL=http://localhost:8080/api npm start

You might wonder how an environment variable on the can be incorporated into the necessary places in the client JavaScript files. There are most likely several ways to do this – one of the simplest is through the webpack DefinePlugin.

Just add & configure the plugin in the webpack.config.json file like this:

1
2
3
new webpack.DefinePlugin({
REST_URL : JSON.stringify(process.env.REST_URL || “/api”)
})

The application is transpiled, packaged and available at http://localhost:3000. This is why the CORS property must be configured properly above.

The development server communicates with your browser via web sockets – so any changes that are made to your code are immediately re-packaged and available to your browser without needing to refresh. Like Magic!

Building the WebApp

The application is packaged together as a Spring Boot runnable jar compiled using Gradle. Installing Gradle manually is not necessary. The application is configured using the gradle wrapper script.

To compile and package the application just run this:

./gradlew bootRepackage on OSX/Linux

gradlew.bat bootRepackage on Windows.

This will download all dependencies, compile/transpile and package all of the code for both the Java REST application and the JavaScript web application into in a runnable jar. The jar file is located in build/libs/packaged-webapp-1.0-SNAPSHOT.jar. This is accomplished by the very helpful gradle plugin that runs npm scripts. The build npm script inside our web application’s package.json will transpile and package all of the front end code as necessary and place it in src/main/resources/static – from which the Spring Boot application is preconfigured to serve static content.

The key is to add the proper gradle build dependencies to run the npm scripts before packaging the entire application into a jar. This is done with the following code in the build.gradle file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
task buildApp(type: NpmTask) {
args = [‘run’, ‘build’]
execOverrides {
it.workingDir = ‘src/main/app’
}
}
task npmClean(type: NpmTask) {
args = [‘run’, ‘clean’]
execOverrides {
it.workingDir = ‘src/main/app’
}
}
clean.dependsOn npmClean
bootRepackage.dependsOn buildApp

After it is packaged running the application is simple:

java -jar build/libs/packaged-webapp-1.0-SNAPSHOT.jar

This will start an embedded webserver (Tomcat) which you can access at http://localhost:8080. You can change the port if necessary by adding the --server.port argument:

java -jar build/libs/packaged-webapp-1.0-SNAPSHOT.jar --server.port=8989

Being able to develop the separate application components both individually and independently provides many benefits. We can have both server side and client developers work concurrently in the same code base. This helps in keeping the REST services and Web application in sync.

Also utilizing Spring Boot to package and run the application simplifies both the building and deployment of the application. A simple gradle command compiles, transpiles, and packages all of the code (server code and client code) together. Deployment is simple – because it’s only one simple jar file and the only dependency is Java. No mucking about with slightly different servlet container configurations on different environments etc.

I’m sure there are other great solutions out there that help ease the burden of developing server/client web applications together and we’d love to hear about them. Let us know in the comments.

If you have any questions about how we’re making this work or questions about the example project feel free to reach out:

You Need to Learn JavaScript

You Need to Learn JavaScript


JavaScript is the most important programming language you can learn.

Now before you summarily dismiss the rest of this article or begin rage commenting – take a breath… and give it 5 minutes. I’m not saying JavaScript doesn’t have problems and I’m not saying it’s necessarily the best programming language. I’m saying it’s the most important. I’ll explain myself in a bit.

First a few clarifications…

JavaScript != jQuery

This was me a few years ago. The only JavaScript I wrote was to manipulate a DOM element here & there. I’m not sure I even knew that an API for the DOM existed outside of what I could do with jQuery. My JavaScript was usually some gnarly spaghetti code spread between a few files and several script tags, but it got the job done where needed. (I would like to formally apologize to those developers who had to maintain that code). I was doing it wrong. I was missing all the good parts because I didn’t know JS. If you are still writing JavaScript spaghetti code (because you can) – you’re also doing it wrong and you’re missing out on some of the language’s greatest strengths – such as code modularization. I will maintain that JavaScript if written correctly is more maintainable and durable than any of your standard class based languages. But that’s a future blog post.

 

JavaScript is a Server-Side language

Ok – yes it’s still a client-side language, but thanks to node.js it runs on the server too. This is kind of a big deal. Look how easy it is to write a web server:

server.js

If some of that syntax looked a little strange it’s because I’m using some es6 features. More on that later. Running JavaScript on both the server and client also allows for the development of Universal/Isomorphic JavaScript applications that share the same codebase on both server and client. Neat!


Ok. Enough with the housekeeping. Now that we’re all together in the wonderful new world of JavaScript possibilities. Let’s get to the meat & potatoes.

 

Top 6 Reasons why JavaScript is the most important language to learn:

1. Functional Programming

Why oh why did it take me this long to discover the beauty (yes beauty) and simplicity of functional programming? Functional Programming encourages writing stateless programs with immutable data structures – which means significantly fewer bugs and more maintainable code. If you want a more in depth look at the benefits of functional programming check out Why Functional Programming Matters – by John Hughes). Yes that paper was written 25 years ago – and probably more relevant today than when he published it. If you don’t have the time right now to read it – then here’s the TL;DR;

Functional Programming allows for modular code which makes simpler, cleaner, better programs.

Yes I know JavaScript is not the only or even the best functional programming language out there. However, I will argue that JavaScript will be the first exposure most developers will ever have to that paradigm. That was certainly true in my case. I was never exposed to languages like Haskell, Clojure, or Erlang, etc.

I’m not sure functional language courses were even offered when I was earning my degree. No – it was All Hail the Mighty Object Orientation using Java and a smattering of C++. JavaScript opened my eyes to the fact that all might not be well in the kingdom of Object Oriented programming. (see also this video, and this post, and any of these articles). JavaScript is everywhere (see item #3 below) and if we teach it correctly – JavaScript will be the vehicle for better software all around. A more in-depth look at Functional Programming will also be forthcoming in a later post.

 

2. Prototypal Inheritance

This one sort of dove-tails off of the last point – but it’s important enough to merit it’s very own bullet point. If you’re not familiar with prototypal inheritance you can read this. But the basic point is this: Prototypal Inheritance gives you the benefits of inheritance without the extra baggage (bugs) that you get with classical inheritance.

Prototypal inheritance is a core feature of JavaScript. It’s incredibly powerful and more performant than alternatives because prototypes are shared among all members lower in the chain. Combine prototypal inheritance with the benefits of functional programming and you’ve got something magic. A classical inheritance heirarchy quickly becomes brittle and difficult to maintain. Programmers cannot predict the future and eventually a feature request will come that you weren’t expecting and will break your taxonomy. I will dig more into this subject in the coming post on functional programming. In the mean time – much smarter people than I have extolled the many virtues of prototypal inheritance — so I’ll direct you to them if you still need convincing:

 

3. Ubiquity

ubiq·ui·ty: presence everywhere or in many places especially simultaneously

Whether you like it or not JavaScript is everywhere. I could show graphs and statistics to demonstrate this, like how it’s the most active language on github, or how it has the largest module repository, but I won’t. The plain fact is that the Web is eating the world and JavaScript is the language of the Web. Even in the burgeoning world of the Internet of Things, JavaScript is a front runner. (Check out cylon.js … so cool). A language that has that much reach can be a powerful force for either propogating bad programming practices & dogma or it can be used to promote better software utilizing the features mentioned above.

 

4. Learnability

That’s totally a real word. Right? Anyway – the ease of learning a language will have a big impact on it’s adoption in the community. A large factor contributing to #3 is that JavaScript is :

  1. easy to obtain
    • All you need to start developing is a browser. You’ve already got that. Most browsers include pretty fancy developer consoles that include console, debugging, and code inspection features. If you want to get a little more serious – just install node.js which comes with npm (package manager) and the REPL runtime. seriously… cake.
  2. easy to learn
    • JavaScript is dynamically-typed, script-based, and (as mentioned above) ubiquitous. That means there’s lots of documentation and examples everywhere. Since it’s a scripting language a new developer can jump right in – no need to learn the specific constructs of creating a program (like figuring out which standard headers to include how to define a main function).
  3. easy to debug
    • I already mentioned the debugger that comes with the browser. Node.js also comes with it’s own debugging api. However – there are several additional modules that make developing and debugging a breeze. (eg. node-inspector, vorlon, nodemon, and browser-sync).

 

5. NPM


I can’t sing enough praises for the Node Package Manager. I’ve talked about the modularity that the functional nature of JavaScript provides. NPM capitalizes on that feature with enormous success. I also mentioned how it is now boasts the largest module repository of any programming language.

Of course JavaScript is not the only language with a package manager or some other type of dependency management, but in my experience it is by far the simplest – and most powerful. Modules are versioned with semantic versioning using a notation that allows you declare the dependencies for your project with varying degrees of specificity for major, minor and patch versions.

Sub-module dependencies are transparently handled by the npm command-line utility which comes bundled with the node installation. The utility also comes with various other commands that allow you install, upgrade, clean, run custom scripts, run test suites, publish, yada, yada…. you get it. It’s all kinds of awesome.

However best feature of NPM in my opinion is the fact that all modules are open source. Aside from the fantastic benefit of the automatic induction into a huge community of developers who share their code openly – this also provides access to hundreds of thousands of examples of functioning modular JavaScript code. If you want to learn how a particular module works (or even better contribute to an open source project) just run

npm install and look at the code – or clone it from the documented repository.

6. ES6

One of the biggest complaints (and in my opinion, the main reason for the existense of jQuery and underscore.js among other libraries) is horrendously slow rate of updates to the language itself. It’s easy to complain, but I can only imagine how difficult this problem has been to solve. Up until recently the sole target for JavaScript was the web browsers, which have historically been incompatible with each other – let alone any kind of single standard. Trying to maintain a language specification to operate in that chaos seems daunting at best.

The good news is that Web Browsers are finally starting to play nicely together (Thank you Microsoft Edge! – I’m now looking at you Safari). TC39 (the group that manages the ECMAScript specification) just released the biggest update to the language since its creation. To prove that they are committed to continuous timely updates they named this release ECMAScript 2015. I know – eww. But I can’t argue with the rationale that it holds them to their commitment to release yearly. I can happily put up with a gross version name in turn for keeping the language polished. All the cool kids are still calling it ES6 anyway.

If you haven’t developed in vanilla JavaScript in some time – now is a fantastic time to come back to the fold. I won’t judge. ES6 offers some fantastic new features that make the language even more powerful. This is another future blog post, but here’s a sneak peek of some of the good stuff:

The astute reader may have noticed that I left out the new class construct that was added in es6. I can not in good conscience recommend this tragedy in any shape or form. Again… this is another post entirely – or you can read this.

 


 

You may not agree with my assertion that JavaScript is the most important language to learn, but I hope to have at least piqued your interest in learning some of the better aspects of the language. My reasons for this assertion is that learning JavaScript will inherently expose you to some of the better programming concepts that you may not find so easily other languages. Stay tuned for a more in depth treatment in many of the topics discussed and let me know your thoughts in the comment section.

Ultimately – “Software needs to be better“. On that note, I’ll leave you with these fine words of wisdom: