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.

Owner
Gitau Harrison
Python | Flask
Gitau Harrison
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 05, 2023
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

Abhishek 6 Sep 27, 2021
This repo contains the Flask API to expose model and get predictions.

Tea Leaf Quality Srilanka Chapter This repo contains the Flask API to expose model and get predictions. Expose Model As An API Model Trainig will happ

DuKe786 2 Nov 12, 2021
A live chat built with python(flask + gevent + apscheduler) + redis

a live chat room built with python(flask / gevent / apscheduler) + redis Basic Architecture Screenshot Install cd /path/to/source python bootstrap.py

Limboy 309 Nov 13, 2022
Neo4j Movies Example application with Flask backend using the neo4j-python-driver

Neo4j Movies Application: Quick Start This example application demonstrates how easy it is to get started with Neo4j in Python. It is a very simple we

Neo4j Examples 309 Dec 24, 2022
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
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

Christian Jairo Sarmiento 19 Dec 02, 2022
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

rebecca 1 Oct 20, 2021
An extension to add support of Plugin in Flask.

An extension to add support of Plugin in Flask.

Doge Gui 31 May 19, 2022
Force SSL on your Flask app.

Flask-SSLify This is a simple Flask extension that configures your Flask application to redirect all incoming requests to HTTPS. The extension is no l

Kenneth Reitz 26 Dec 07, 2022
Track requests to your Flask website with Matomo

Flask-Matomo Flask-Matomo is a library which lets you track the requests of your Flask website using Matomo (Piwik). Installation pip install flask-ma

Lucas Hild 13 Jul 14, 2022
Brandnew-flask is a CLI tool used to generate a powerful and mordern flask-app that supports the production environment.

Brandnew-flask is still in the initial stage and needs to be updated and improved continuously. Everyone is welcome to maintain and improve this CLI.

brandonye 4 Jul 17, 2022
An python flask app with webserver example

python-flask-example-keepalive How it works? Basically its just a python flask webserver which can be used to keep any repl/herokuapp or any other ser

KangersHub 2 Sep 28, 2022
Regex Converter for Flask URL Routes

Flask-Reggie Enable Regex Routes within Flask Installation pip install flask-reggie Configuration To enable regex routes within your application from

Rhys Elsmore 48 Mar 07, 2022
:rocket: Generate a Postman collection from your Flask application

flask2postman A tool that creates a Postman collection from a Flask application. Install $ pip install flask2postman Example Let's say that you have a

Numberly 137 Nov 08, 2022
Full text search for flask.

flask-msearch Installation To install flask-msearch: pip install flask-msearch # when MSEARCH_BACKEND = "whoosh" pip install whoosh blinker # when MSE

honmaple 197 Dec 29, 2022
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

4.3k Jan 06, 2023
Flask Application Structure with MongoDB

This application aims to serve as a template for APIs that intend to use mongoengine and flask-restx

Tiago Franco 5 Jun 25, 2022
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
Flask-Diamond is a batteries-included Flask framework.

Flask-Diamond Flask-Diamond is a batteries-included Python Flask framework, sortof like Django but radically decomposable. Flask-Diamond offers some o

Diamond Methods 173 Dec 22, 2022