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
A Microsub server built with Python Flask and SQLite.

Microsub Server This repository contains the code that powers my personal Microsub server. Microsub is an IndieWeb specification currently in developm

jamesg 8 Oct 26, 2022
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
Library books management program, built with Flask, Python

Library books management program, With many features and good User Interface. built with Flask, Python. (Include Screenshots) and documentation on how to run it! Thank you :)

Thierry Mugisha 1 May 03, 2022
Boilerplate template formwork for a Python Flask application with Mysql,Build dynamic websites rapidly.

Overview English | 简体中文 How to Build dynamic web rapidly? We choose Formwork-Flask. Formwork is a highly packaged Flask Demo. It's intergrates various

aswallz 81 May 16, 2022
iloveflask is a Python library to collect functions that help a flask developer generate reports, config files and repeat code.

I Love Flask iloveflask is a Python library to collect functions that help a flask developer generate reports, config files and repeat code. Installat

2 Dec 29, 2021
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
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication. For use with cookiecutter.

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 Dec 29, 2022
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-

Kushagra Bainsla 5 Jul 16, 2022
A simple example using Flask inside a container

This is a simple example of how create a container for a Python Flask Web Application using Docker.

Fazt Web 8 Aug 30, 2022
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 365 Jan 06, 2023
A flask app that turn image into ASCII art

ASCII art A flask app that turn image into ASCII art. This app has been deployed to https://motmaytinh.herokuapp.com Getting Started These instruction

Trần Ngọc Quý 1 Jan 13, 2022
A simple Task todo application built with Flask

Task TODO Table An application built with Flask a Python framework and hosted on Heroku. Important notes GuniCorn (Green Unicorn): is a Python WSGI HT

DCN (Dubem Celestine Nwabuisi) 1 Dec 15, 2021
5 Flask Projects To Get Started

5 Flask Projects Projects Made By Using Flask Projects List Rock Paper Scissor Game - A Simple Game Weather App - A OpenWeatherMap Scraper Task List -

Root_Arch 59 Dec 18, 2022
Flask Multiple Database Login

Flask Multiple Database Login Handle login with flask using two diferent databases: UE | European; BR | Brazilian; These databases are separed to resp

Jose Pedro 1 Dec 16, 2021
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

249 Jan 06, 2023
Easy file uploads for Flask.

Library that works with Flask & SqlAlchemy to store files on your server & in your database Read the docs: Documentation Installation Please install t

Joe Gasewicz 145 Jan 06, 2023
MongoEngine flask extension with WTF model forms support

Flask-MongoEngine Info: MongoEngine for Flask web applications. Repository: https://github.com/MongoEngine/flask-mongoengine About Flask-MongoEngine i

MongoEngine 815 Jan 03, 2023
Rubik's cube assistant on Flask webapp

webcube Rubik's cube assistant on Flask webapp. This webapp accepts the six faces of your cube and gives you the voice instructions as a response. Req

Yash Indane 56 Nov 22, 2022
Flask app for deploying DigitalOcean droplet using Pulumi.

Droplet Deployer Simple Flask app which deploys a droplet onto Digital ocean. Behind the scenes there's Pulumi being used. Background I have been Terr

Ahmed Sajid 1 Oct 30, 2021
Telegram bot + Flask API ( Make Introduction pages )

Introduction-Page-Maker Setup the api Upload the flask api on your host Setup requirements Make pages file on your host and upload the css and js and

Plugin 9 Feb 11, 2022