Don't waste time creating multiple popups for changing content - streamline your process

Challenge

I've successfully extracted information from an array and displayed it dynamically in a tooltip/popup window above each photo on the page. However, with 56 different individuals at various locations, arranging them neatly in a grid poses a challenge.

Inquiry

a) Is there a way to streamline the creation of tooltips for each person so that clicking on their image will display the tooltip with relevant dynamic content?

scripts.js

    $(function() {

        // MLAs
        var MLAs = [
          {
            "Name": "Nancy Allan",
            "Age": 62,
            "Constuency": "St. Vital",
            "Party": "NDP",
            "Gender": "Female",
            "Ethnicity": "White"
          },
          {
            "Name": "James Allum",
            "Age": null,
            "Constuency": "Fort Garry-Riverview",
            "Party": "NDP",
            "Gender": "Male",
            "Ethnicity": "White"
          },
          {
            "Name": "Rob Altemeyer",
            "Age": null,
            "Constuency": "Wolseley",
            "Party": "NDP",
            "Gender": "Male",
            "Ethnicity": "White"
          }]

        // Display popup with MLA info
        $(".headshot").click(function(){
            var idx = $(this).index() - 1;

            $(".tooltip").fadeIn("slow");
            $(".tooltipName").html(MLAs[idx].Name);
            $(".tooltipParty").html(MLAs[idx].Party);
            $(".tooltipConstuency").html(MLAs[idx].Constuency);
            $(".tooltipEthnicity").html(MLAs[idx].Ethnicity) + ",";
            $(".tooltipAge").html(MLAs[idx].Age);
        });

    // Positioning of tooltips
    $('.headshot').each(function(){
        var img = $(this);

        img.click(function(){
            $('.tooltip')
            .show(100)
            .text(img.attr('alt'))
            .offset({
                top : img.offset().top + img.height(),
                left : img.offset().left
            });
        });
    });
 });

index.html

            <div class="tooltip">
                <div class="info">
                    <p class="tooltipName"></p>
                    <p class="tooltipParty"></p> <p class="tooltipConstuency"></p>
                    <p class="tooltipEthnicity"></p> <p class="tooltipAge"></p>
                    </div><!-- /.info -->

                    <div class="arrow-down">
                    </div><!-- /.arrow-down -->
                </div><!-- /.tooltip -->

<img src="assets/img/headshots/allan.jpg" alt="" id="0" class="headshot NDP Female White">
                <img src="assets/img/headshots/allum.jpg" alt="" id="1" class="headshot NDP Male White">
                <img src="assets/img/headshots/altemeyer.jpg" alt="" id="2" class="headshot NDP Male White">

tooltip.scss

/*----------------------------------
TOOLTIP
----------------------------------*/

.tooltip {
    display: none;
    position: relative;
    left: -12px;
    top: -5px;
}

.info {
    @include serifLight;
    background: $yellow;
    color: $black;
    font-size: 1.4rem;
    padding: 10px;
    width: 9%;
    text-align: center;

    p {
        margin: 0px;
    }
}

.tooltipName, {
    font-family: 'Roboto Slab',serif;
    font-weight: 700;
}

.tooltipEthnicity, .tooltipAge {
    display: inline;
}

.arrow-down {
    width: 0;
    height: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-top: 20px solid $yellow;
    position: relative;
    left: 36px;
}

Answer №1

If you want to customize the position of the tooltip, you can utilize the .offset() values.

Check out this example on JSFiddle

$('img').each(function(){
    var img = $(this);

    img.click(function(){
             $('.tooltip')
             .show(100)
             .text(img.attr('alt'))
             .offset({
                top : img.offset().top + img.height(),
                left : img.offset().left
        });
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with jQuery not running properly in your jsFiddle code?

Check out this link for some basic jQuery code I'm testing in jsFiddle. However, I keep getting an exception saying that text is not a function: <div class="animals"> <div class="cats"> <div class="lions"> meow < ...

Querying an API for JSON data repeatedly until a particular key is located

I am currently in the process of working on a submission-based project where tasks are performed using the submitted content. While a details/results page is generated immediately after submission (the job being queued), the results may not be readily avai ...

Having trouble incorporating a JavaScript snippet from Google Trends into an HTML webpage

Hey everyone, I've been trying to incorporate a JavaScript script to display Google Trends on an HTML page. I copied the embed code directly from the first image at and modified it as follows. Unfortunately, it's not working as expected. <ht ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

Is there a way to conceal JavaScript code?

I am trying to keep my AJAX code hidden from users who view the source of my PHP page. How can I achieve this? Below is the AJAX code that I currently have: <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=n ...

Having a newline between HTML elements can disrupt the structure of an HTML layout

It's common knowledge that in html, a newline between elements is treated as space. However, I find it quite alarming when working on responsive layouts. For instance, take a look at this example where the expected and correct behavior is achieved on ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

A guide on populating a dropdown menu with spring and hibernate in JSP

I'm a newcomer here and seeking ideas from you all. I have 4 dropdown lists and want to populate one select box based on the selection made in another select box using database values. I have already set up the database, but unsure how to proceed. Any ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

The Ultimate Guide to Setting up SVG's Viewbox, Width, and Height for Scalability and Responsiveness

As a beginner in SVG design, I find it challenging to scale, zoom in/out with the container and ensure responsiveness across different devices. I wonder if it's possible to create an SVG that adapts to all device sizes and effectively handles browsin ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

Getting a page element by its id with QWebEngineView is a simple task that can be

Is there a way to access the page ElementById in order to input a value? import sys from PyQt5 import QtWebEngineWidgets from PyQt5.QtCore import * from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import * from PyQt5.QtWidgets import QAction from PyQt ...

Exploring the Possibilities of Socket.io Integration with Express 4 Across Multiple Pages: Dive Into Socket.io Sample Code

Just to clarify, I came across a similar question on Stack Overflow before posting this. However, the answer there was not clear to me and my query is slightly different. Thus, I am hoping for a more straightforward explanation. The Express Generator sets ...

Adding Components Dynamically to Angular Parent Dashboard: A Step-by-Step Guide

I have a dynamic dashboard of cards that I created using the ng generate @angular/material:material-dashboard command. The cards in the dashboard are structured like this: <div class="grid-container"> <h1 class="mat-h1">Dashboard</h1> ...

The page reloads automatically following the completion of an ajax request

Hey there, I have a basic form with just a text field. When we submit the form, the data entered in the text field gets stored in the database through ajax. Although the ajax function is working properly and the data is being submitted, the page automatica ...

Confirming the accuracy of multiple fields in a form

Looking for help with validating both password and email fields on a registration form. I've successfully implemented validation for passwords, but need assistance adding validation for the email section as well. Can both be validated on the same form ...

VueJS - Iterating over a list within a vue component causes the list to be empty

Having encountered an issue with the answers provided to my question from yesterday, I have decided to create a new query with additional details. To review the original question, please visit: VueJS - using mustache template strings inside href attribute ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

What is the best way to ensure my jQuery plugin is up to date?

I have a question regarding the functionality of this plugin I am using. My goal is to update the timer it provides. To start the countdown timer with 5000 milliseconds remaining, I use the following code: $('#CountdownTimer').countdown({ remai ...