A fairly common feature in web applications to have links that open a popover when hovered

Overview

Add Popovers to Links in Flask App

It is a fairly common feature in web applications to have links that open a popover when hovered. Twitter does this, Facebook does it, LinkedIn does it. Popovers are a great way to provide additional information to users.

Popover

Features

  • User Registration and authentication
  • Profile popovers

Tools Used

  • Flask framework
  • Python for programming
  • Flask-Bootstrap
  • Flask-WTF
  • Flask-SQLAlchemy
  • Flask-Login
  • Flask-Migrate
  • Flask-Moment
  • Email validator
  • Python-dotenv
  • Ajax requests

Contributors

GitHub Contributors

Testing the Deployed Application

You can use the following credentials to test the deployed application:

  • Username: harry
  • Password: 12345678

Alternatively, you can create your own user by clicking the Register link. You will be redirected to the Login page automatically where you can authenticate that user.

Testing the Application Locally

  1. Clone this repository:

    $ git clone git@github.com:GitauHarrison/flask-popovers.git
  2. Change into the directory:

    $ cd flask-popovers
  3. Create and activate a virtual environment:

    $ virtualenv venv
    $ source venv/bin/activate
    
    # Alternatively, you can use virtualenvwrapper
    $ mkvirtualenv venv
    • Virtualenvwrapper is a wrapper around virtualenv that makes it easier to use virtualenvs. mkvirtualenv not only creates but also activates a virtual enviroment for you. Learn more about virtualenvwrapper here.

  4. Install dependencies:

     ```python
     (venv)$ pip install -r requirements.txt
     ```
    
  5. Add environment variables as seen in the .env-template:

     ```python
     (venv)$ cp .env-template .env
     ```
    
    • You can get a random value for your SECRET_KEY by running python -c "import os; print os.urandom(24)" in your terminal.

  6. Run the application:

    (venv)$ flask run
  7. Open the application in your favourte browser by copying and pasting the link below:

  8. Feel free to create a new user and see the popovers in action. You can do so by registering a user then logging in.

How To

Select Element

To create a popover on a link, you first need to identify what link exactly you want to have a popover. You can do this by adding the class selector on an element. For example, if you want to add a popover to the link /user/ , you would add the following to the element:

{{ post.author.username }} ">
<span class="user_popup">
    <a href="{{ url_for('user', username=post.author.username) }}">
        {{ post.author.username }}
    a>
span>

In the example above, I have modified how I select the link I want to have a popover. This is deliberate. Typically, I would have done:

{{ post.author.username }} ">
<a class="user_popup" href="{{ url_for('user', username=post.author.username) }}">
        {{ post.author.username }}
a>

But this has the ugly effect where the popover will acquire the behaviour of the parent element. This is not desirable. I will end up with something that looks like this:

{{ post.author.username }}
">
<a href="" class="user_popup">
    <a href="{{ url_for('user', username=post.author.username) }}">
        {{ post.author.username }}

        <div>  div>
    a>
a>

Typically, making the popover a child of the hovered element works perfectly for buttons and generally

and .

Hover Event

Using JQuery, a hover event can be attached to any HTML element by calling the element.hover(handlerIn, handlerOut) method. JQuery can also conviniently attach the events if the functions are called on a collection of elements.

$('.user_popup').hover(
    function(){
        // Mouse in event handler
        var elem = $(event.currentTarget);
    },
    function(){
        // Mouse out event handler
        var elem = $(event.currentTarget);
    }
)

Ajax Request

When using JQuery, $.ajax() function is used to send an asynchronous request to the server. An example of a request can be /user/ /popup . This request contains HTML that will be inserted into the popover.

$(function() {
        var timer = null;
        var xhr = null;
        $('.user_popup').hover(
            function(event) {
                // mouse in event handler
                var elem = $(event.currentTarget);
                timer = setTimeout(function() {
                    timer = null;
                    xhr = $.ajax(
                        '/user/' + elem.first().text().trim() + '/popup').done(
                            function(data) {
                                xhr = null
                                // create and display popup here
                            }
                        );
                }, 500);
            },
            function(event) {
                // mouse out event handler
                var elem = $(event.currentTarget);
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                else if (xhr) {
                    xhr.abort();
                    xhr = null;
                }
                else {
                    // destroy popup here
                }
            }
        )
    });

The $.ajax() call returns a promise, which essentially is a special JS object that represents asynchronous operation.

Create Popover

data argument passed by the $.ajax() call is the HTML that will be inserted into the popover.

function(data) {
    xhr = null;
    elem.popover({
        trigger: 'manual',
        html: true,
        animation: false,
        container: elem,
        content: data
    }).popover('show');
    flask_moment_render_all();
}

The return of the popover() call is the newly created popover component. flask_moment_render_all() function is used to display the last time a user was active.

Destroy Popover

If the user hovers away from the popover, the popover will be aborted. This is done by calling the .popover('destroy') method.

function(event) {
    // mouse out event handler
    var elem = $(event.currentTarget);
    if (timer) {
        clearTimeout(timer);
        timer = null;
    }
    else if (xhr) {
        xhr.abort();
        xhr = null;
    }
    else {
        elem.popover('destroy');
    }
}

Reference

If you would like to see how the application above has been built, you can look at this flask popover tutorial.

You might also like...
Boilerplate code for basic flask web apps

Flask Boilerplate This repository contains boilerplate code to start a project instantly It's mainly for projects which you plan to ship in less than

A simple FastAPI web service + Vue.js based UI over a rclip-style clip embedding database.
A simple FastAPI web service + Vue.js based UI over a rclip-style clip embedding database.

Explore CLIP Embeddings in a rclip database A simple FastAPI web service + Vue.js based UI over a rclip-style clip embedding database. A live demo of

A Flask web application that manages student entries in a SQL database

Student Database App This is a Flask web application that manages student entries in a SQL database. Users can upload a CSV into the SQL database, mak

Set up a modern flask web server by running one command.
Set up a modern flask web server by running one command.

Build Flask App · Set up a modern flask web server by running one command. Installing / Getting started pip install build-flask-app Usage build-flask-

A web application made with Flask that works with a weather service API to get the current weather from all over the world.
A web application made with Flask that works with a weather service API to get the current weather from all over the world.

Weather App A web application made with Flask that works with a weather service API to get the current weather from all over the world. Uses data from

Are-You-OK is a Flask-based, responsive Web App to monitor whether the Internet Service you care about is still working.
Are-You-OK is a Flask-based, responsive Web App to monitor whether the Internet Service you care about is still working.

Are-You-OK Are-You-OK is a Flask-based, responsive Web App to monitor whether the Internet Service you care about is still working. Demo-Preview Get S

A web application for a fake pizza store, built in Python with Flask and PostgreSQL.
A web application for a fake pizza store, built in Python with Flask and PostgreSQL.

✨ Pizza Pizza - Pizza Store ✨ A web application for a fake Pizza Store, the app let you create an account and order pizza, complements or drinks. Buil

This is a simple web application using Python Flask and MySQL database.

Simple Web Application This is a simple web application using Python Flask and MySQL database. This is used in the demonstration of development of Ans

Owner
Gitau Harrison
Python | Flask
Gitau Harrison
SQLAlchemy database migrations for Flask applications using Alembic

Flask-Migrate Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations

Miguel Grinberg 2.2k Dec 28, 2022
Quick and simple security for Flask applications

Note This project is non maintained anymore. Consider the Flask-Security-Too project as an alternative. Flask-Security It quickly adds security featur

Matt Wright 1.6k Dec 19, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 2, 2023
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.1k Feb 17, 2021
Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications.

Flask Sitemapper Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications. This allows you to create a nice and

null 6 Jan 6, 2023
Flask Project Template A full feature Flask project template.

Flask Project Template A full feature Flask project template. See also Python-Project-Template for a lean, low dependency Python app. HOW TO USE THIS

Bruno Rocha 96 Dec 23, 2022
Browsable web APIs for Flask.

Flask API Browsable web APIs for Flask. Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API S

Flask API 1.3k Jan 5, 2023
Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.

Flask-Starter Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development. It has all the r

Kundan Singh 259 Dec 26, 2022
Burp-UI is a web-ui for burp backup written in python with Flask and jQuery/Bootstrap

Burp-UI Contents Introduction Screenshots Demo What's that? Who are you? Documentation FAQ Community Notes See also Licenses Thanks Introduction Scree

Benjamin 84 Dec 20, 2022
Intranet de la Rez Flask web app

IntraRez Application Flask de l'Intranet de la Rez. Exigences Python : Probablement >= 3.10 à terme, pour l'instant >= 3.8 suffit ; Autres packages Li

null 3 Jul 3, 2022