HOWTO: Use jQuery to Scroll to a Target HTML Element

jquery tip

A common request when working on a web site or application, is to have some kind of “auto-scroll” effect. In other words, I’m talking about that thing where you click a button or navigation item, and the page takes a few hundred milliseconds to gently scroll up/down to an element.

Perhaps you want to highlight your CTA (eg. Call to Action), etc.

Let’s take care of this with a trivial amount of jQuery!

Option A: Add some small jQuery

Once jQuery is included / loaded on the page, we can tap into the animate() method to create some nice smooth scrolling.

Let’s look at the following:


  $(function() {
     $('.scroll').on('click', function(e) {
        e.preventDefault();
        var offset = $(this).data('offset') || 0;
        var target = this.hash;
        $('html, body').stop().animate({
            'scrollTop': $(target).offset().top - offset
        }, 500);
     });
  });

I’ve added an offset parameter here, to allow you to specify via a data- attribute an offset to your target element. This can be handy if you want to scroll up/down to a target element, but stop a small bit of distance before it.

With this snippet in place, now we can enhance a navigation element.

Let’s look at a basic use of our new click handler:


<a class="scroll" href="#targetElement">Scroll to Target</a>

So at this point, some simple scroll handling is in place. Clicking on that link will cause the page the scroll to whatever target element you specify.

Now let’s add an offset. Sometimes when you tinker with page scrolling this way, it can create a bit of “weirdness” depending on your existing CSS. The page scrolls properly, but maybe the way your target element is positioned, the page is just a touch too high or low. This is where the offset helps us out.

Let’s update our snippet to specify that offset:


<a class="scroll" href="#targetElement" data-offset="200">Scroll to Target</a>

Now in this example, if you click the link, the page will scroll to a point 200 pixels above the target element.

Option B: Use the jQuery.scrollTo Plugin

A properly written jQuery Plugin will usually “play nice” with any existing JavaScript on the page, so another option is to grab the jQuery.scrollTo plugin.

Hope you enjoyed this tip, please like and share it!

HOWTO: Build Your Own jQuery Plugin

jquery tip

After enough time of working with jQuery code and sites, you might start to notice that you have similar jQuery code in a bunch of projects. You always include some scrolling, or animations to various similar link styles, etc.

If only there was some way to create a “library” that you can then just include into all your projects with a single snippet…

Turns out – you can with jQuery Plugins.

jQuery Object Methods

Before we go through the process of creating a plugin, let’s dig a little into how jQuery actually works to begin with.

Let’s look at a small snippet:


$(".panel").css("color", "blue");

This is a simple enough sliver of jQuery code. We’re binding to all elements of the class panel and modifying the CSS color attribute to blue. Whenever you use the $ function to select elements, it’s returning a jQuery object. This particular object contains all of the methods that you have been regularly using (eg. .css(), .click(), .show(), .hide(), etc) and all of the elements that fit the given selector.

The jQuery object obtains these methods from the$.fn object. This object contains all of the jQuery object methods, and any other methods from any jQuery plugin that is also being loaded by the site.

In other words, we want to attach any of our own plugin code to the $.fn object so that it’s accessible throughout the site.

Let’s test this out. We can add an object function called bordify:

  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
  };

  // then somewhere in our code we can do...
  $("a").borderify();

NB: note that to use the .attr() method, we can use this directly, rather then wrapping it with $(this). That is because the borderify function is now a part of the same object as .attr().

Making Chainable

The borderify object function “works”, but there are a few problems if we released this “as is” to the world. One issue is that we internally break the object chaining that the existing jQuery methods support and promote.

For example, it’s not uncommon to link (chain) together 3 or 5 functions onto a single selector.

This is allowed, because almost all of the $.fn object methods return the original jQuery object.

Let’s update our borderify to support proper chaining:

  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
    return this;
  };

  // then somewhere in our code we can now do...
  $("a").borderify().addClass("notice");

Protecting the $

We still have an additional problem. While most JavaScript libraries now avoid ALSO using the $, we are building our code, based on the assumption that $ IS the jQuery $ and NOT a different library.

To make sure our plugin stays properly working within any environment we drop this script into, we need to stick our method into an IIFE (Immidiately Invoked Function Expression) - which is a body of JavaScript that is executed immidiately upon being parsed by the browser JavaScript interpreter.


(function($) {
  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
    return this;
  };
} (jQuery));

Privacy

We’re on a good track now with our plugin. Because our code is within an IIFE, we can now make use of our own private variables or functions that won’t be exposed outside of this block.


(function($) {
  var border_color = "#6495ed";

  function some_other_private_function(a, b) {
     return a + b;
  }

  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px " + border_color });
    return this;
  };
} (jQuery));

Staying Safe

It can quickly become tempting to create addition methods within our library, and attach them all to the $.fn object. However, you have to consider (and remember) that your plugin code could be dropped into a site with dozens of other jQuery plugins. All of them appending themselves to the $.fn. As such, there is a possibility that another plugin will try using the same object name as you, which will then override your plugin code with the other plugin.

To be as safe as you can, try to attach only one object function to the $.fn object within your plugin.

Allowing for Options

Depending on the complexity of your plugin, it might be a good idea to allow some customization by accepting an options object. One of the simplest ways is to allow the use of a JavaScript object literal.

Let’s take a look:


(function($) {
  $.fn.borderify = function( options ) {
    var settings = $.extend({
       // These are the defaults
       borderStyle: "dotted",
       borderWidth: "1px",
       borderColor: "#6495ed"
    }, options );
    this.attr({ "style": "border: " + options.borderStyle + " " + borderWidth + " " + border_color });
    return this;
  };
} (jQuery));

That Wraps it Up

This wraps up our simple guide to making your own jQuery plugin. Hopefully it’s sparked some ideas for you. Feel free to let us know what plugin you end up creating! Go for it!

Like what you see? Share it with your friends!

Installing Postgresql on Raspberry Pi

PostgreSQL is a popular database option used teams and companies of all sizes. From the smallest of hobbyist projects, to the largest of Enterprise online web applications.

In this tutorial, I’m going to explain how to install the latest Postgresql on the Raspberry Pi. I’m going to assume that you have Raspbian installed on your Raspberry Pi.

Installing the Essentials

In an open Terminal session window, type the following command to install PostgreSQL:

sudo apt update
sudo apt install postgresql

Wait until the installation process is finished. Part of the installation process will involve the setup of PostgreSQL as a system service. Once the installation has finished, you can verify it’s running via:

sudo systemctl status postgresql

You should see something like this:

pi@raspberrypi:~ $ sudo systemctl status postgresql
 postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor prese
Active: active (exited) since Sat 2019-09-21 15:53:47 MDT; 38min ago
Process: 4031 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 4031 (code=exited, status=0/SUCCESS)
CPU: 0
CGroup: /system.slice/postgresql.service

Sep 03 15:53:47 raspberrypi systemd[1]: Starting PostgreSQL RDBMS...
Sep 03 15:53:47 raspberrypi systemd[1]: Started PostgreSQL RDBMS.

It is really that simple; PostgreSQL has been installed!

Connect to the PostgreSQL console

In an open Terminal session window, use this command to connect to PostgreSQL the running console.

sudo -i -u postgres

Still connected to the console, you can run psql to help verify what version you’re working with:

postgres@raspberrypi:~$ psql
psql (11.5 (Raspbian 11.5-1+deb10u1))
Type "help" for help.

postgres=#

You can display a list of all the current databases.

\l

Since we haven’t added one, you should see a list of 3 databases.

To quit the console, just type \q.

Enable Networking for PostgreSQL

In most cases, your PostgreSQL database will be accessed through a web application server running on the same machine - such as through PHP, Node, Ruby on Rails, etc. In which case, you don’t have to do any further PostgreSQL configuration.

To allow your PostgreSQL databases to be accessed from the network via TCP/IP, you’ll need to make a simple change to a configuration file. Open the following file with nano:

nano /etc/postgresql/11/main/postgresql.conf

Find the following line:

listen_addresses = 'localhost'

Update it to:

listen_addresses='*'

Close and save the file with ctrl+x. Finally, restart the running PostgreSQL service.

sudo systemctl restart postgresql

Done.

Conclusion

Hopefully this was a simple walkthrough to show you how to setup the latest version of the PostgreSQL database on your Raspberry Pi.