Guide to updating text below an image upon clicking/hovering on the image

I am working on a project for a company that showcases the four founders with their pictures displayed side by side. The requirement is to have the text under each image change dynamically based on which photo is clicked or hovered over. For example, when you click on "Mark", his name will be displayed in bold along with his qualifications. However, this information will be replaced once you click on "Kim" who is the next picture. As someone new to HTML, CSS, and JavaScript, this task is my first attempt at integrating all three languages.

I aim to style the text exactly as I desire, but I am struggling to find a way to update it in real-time. So far, I have only managed to print raw text. Is there a method to call a div to display the text and replace it with a new div upon clicking each image?

Instead of using .html("Mark does xyz"), could I potentially insert the entire "tr1" div with the updated button, heading, and paragraph?

<div id="trainers">
        <h1><b>Meet Our Trainers</h1>
        <img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%">
        <img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%">


<div id="tr1">
  <h1><b><br>Mark</b></h1>
  <p>Mark has been a personal trainer</p>
  <a class="btn" href="#">Book With Mark</a>
</div>
<div id="tr2">
  <h1><b><br>Kim</b></h1>
  <p>Kim is a nutritionist</p>
  <a class="btn" href="#">Book With Kim</a>
</div>
</div>






<script>
    $('#Mark').click(function() {
    });

    $('#Kim').click(function() {
    });

</script>

Answer №1

If you want to achieve your goal, the show/hide method can be helpful.

$('#Mark').click(function() {
   $('#tr1').show();
   $('#tr2').hide();
});

$('#Kim').click(function() {
   $('#tr1').hide();
   $('#tr2').show();
});

$('#Mark').click(function() {
       $('#tr1').show();
       $('#tr2').hide();
    });

    $('#Kim').click(function() {
       $('#tr1').hide();
       $('#tr2').show();
    });
#tr2{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trainers">
        <h1><b>Meet Our Trainers</h1>
        <img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%">
        <img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%">


<div id="tr1">
  <h1><b><br>Mark</b></h1>
  <p>Mark has been a personal trainer</p>
  <a class="btn" href="#">Book With Mark</a>
</div>
<div id="tr2">
  <h1><b><br>Kim</b></h1>
  <p>Kim is a nutritionist</p>
  <a class="btn" href="#">Book With Kim</a>
</div>
</div>

Answer №2

$('#Mark').on('click', function() {
    var elementToCopy = document.getElementById('tr1');
    var copy = elementToCopy.cloneNode(true);
    var placeholder = document.getElementById('placeholder');

    // Now you need to insert the copied element into a designated placeholder on the webpage.

    placeholder.appendChild(copy);       
});

The placeholder mentioned here should be an element in your HTML that does not currently exist. It will serve as the location where the cloned HTML content will be placed:

<div id="placeholder"></div>

This process allows you to duplicate the necessary HTML and position it accordingly on the page. When you click on a different image, it is essential to remove the existing HTML, clone the alternative one, and append it to the placeholder. Additionally, consider using an if statement to verify if the placeholder already contains content.

Since your query involves jQuery, this response employs the jQuery on method. Ensure that jQuery is properly included if necessary.

An alternative approach involves utilizing vanilla JavaScript click event methods:

<img id="Mark" onclick="performHTMLInsertion()" src="foo.jpg" />

Alternatively,

document.getElementById('Mark').addEventListener('click', performHTMLInsertion);

Answer №3

If you want to utilize JQuery for this task, the code snippet below will help achieve the desired outcome. It involves using a common class called "trainer-text" to initially hide overlay texts. Additionally, some CSS can be applied to style text on images. Visit the following link for further guidance: https://www.w3schools.com/howto/howto_css_image_overlay.asp

/*
    Use the following if you need display text for hover event
*/
$("#Mark").mouseover(function(){
    $("#tr1").css("display", "block");
});
$("#Mark").mouseout(function(){
    $("#tr1").css("display", "none");
});
$("#Kim").mouseover(function(){
    $("#tr2").css("display", "block");
});
$("#Kim").mouseout(function(){
    $("#tr2").css("display", "none");
});

/*
    Use the following if you need display text for click event
*/
$('#Mark').click(function() {
    $('#tr1').show();
    $('#tr2').hide();
});

$('#Kim').click(function() {
    $('#tr1').hide();
    $('#tr2').show();
});
.trainer-text {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trainers">
    <h1><b>Meet Our Trainers</b></h1>
    <img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%"/>
    <img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%"/>

    <div id="tr1" class="trainer-text">
        <h1><b><br>Mark</b></h1>
        <p>Mark has been a personal trainer</p>
        <a class="btn" href="#">Book With Mark</a>
    </div>
    <div id="tr2" class="trainer-text">
        <h1><b><br>Kim</b></h1>
        <p>Kim is a nutritionist</p>
        <a class="btn" href="#">Book With Kim</a>
    </div>
</div>

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

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Exploring the process of iterating through and organizing a JavaScript array

Recently, I encountered a JavaScript object that was generated by a particular API. The object is structured in a way that it can potentially have multiple instances of the same 'equity' (such as Hitachi Home in this case): { "results": { ...

Is there a way to temporarily halt scrolling text and then resume?

Is there a way to pause the marquee for a few seconds at the end of each <li>, before continuing on to the next one? Here's my code: <div id="teks_container" > <marquee direction="up" scrollamount="3" height="200px"> <ul&g ...

Getting the price of a variation based on its ID within an ajax request

I'm having trouble retrieving the price of a variation using its ID within an ajax call. I'm puzzled as to why wc_get_product() is not returning the expected object. Below is my JavaScript code for the ajax call: $(document).on('change&apos ...

Create an array in JavaScript using the JSON data that was returned

After receiving some JSON data from a REST call, I have successfully parsed and added totals to the data. The results can be viewed on the page (refer to this post: json sibling data). However, now I want to further break down the totals. Here is the initi ...

Grouping results by month according to the datetime object in C#

I am working on an ASP.NET MVC application that includes a line chart displaying record counts and months on the X-axis and Y-axis respectively. To achieve this, I need to make an ajax call to the controller where the model holds information such as the r ...

Steps to update the color of checkbox labels

I'm struggling with changing the colors of checkbox values based on their status - when checked, I want the text to display in green, and when unchecked, I want it to be red. Below is a sample input type, but I can't figure out how to style the t ...

Dynamic data management through PHP, Ajax, and jQuery for database tables

I have a database called "guests" that consists of two columns: Seat and Name. My goal is to display this database on a php page where users can double click on the "name" value to edit it, with the changes being updated in the database when they click el ...

The HTML code is failing to load the font

I'm having trouble with the font on my website not loading properly. I added the Abel font family to my code, but it doesn't seem to be working. Here is a snippet of what I have tried: <p style="margin-left: 620px; margin-top: -355px;" ...

Placing text beside an image

I am brand new to osCommerce and recently took over this code. We are looking to improve the layout of the new_products page. Here is the current display code: div class="contentText"> <div class="NewProductsList"> <table border="0 ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

Yet another method for transferring arguments in typescript

I have a TypeScript class with a method that takes three arguments. class MyClass { public static carStatus(name : string , color : string , isReady : boolean){ let result = isReady ? 'is ready' : 'is not ready'; return `${co ...

Positioning an image alongside a row in a table

Looking to incorporate images alongside each row in a table using Html and CSS, similar to the example image below: https://i.sstatic.net/fASNr.png The desired placement for the images is depicted by the red crosses: positioned on the right side of each ...

CSS is not referred to as animation

Every time we hit a key, the dinosaur receives a jump class that should activate an animation. Unfortunately, the animation does not play. animation not functioning <!DOCTYPE html> <html lang="en"> <head> <meta c ...

Having trouble viewing PDF files after uploading them to S3. Uploading images is working without any issues in NodeJS

For a while now, I've been using the aws-sdk to upload images with no issues. However, I recently tried to upload a PDF and encountered a problem. Even though the upload seems successful, I get an error message saying Failed to load PDF document. I a ...

Firestore information does not appear visible

I encountered an issue with my custom hook where I am fetching images from a Firestore collection. Everything was working smoothly until I attempted to retrieve the metadata of the images as well. The problem arose when I included the getMetaData function, ...

What steps can I take to prevent divs from changing when hovered over individually?

Firstly, I am open to any superior suggestions that could save me some time and effort. My goal is to create a vertically oriented circular/elliptical carousel. Despite my extensive searching on Google for days, I have not come across anything similar, wh ...

Is there an issue with my straightforward AJAX demonstration? Must your website be hosted on a server for it to work properly?

I'm having trouble understanding what's causing the issue as all my files are located in the same directory. I'll begin by sharing the HTML code, followed by the AJAX script, and lastly, the .txt file contents. HTML: <!doctype html> ...

Arrange the array of tasks in the Gantt schedule by sorting them according to the combination of date and duration, while considering any static breaks that

i am working on an array that represents a gantt schedule. Each object in the array has specific properties { id: string; startTime: Date; durationEstimated: number; isBreak: boolean; } and some generalized values. I have to iterate throu ...

Sorting with jQuery UI - execute action on drag start and clear on drop

I am currently working with two blocks: one is "draggable" and the other is "sortable". My goal is to add a background color to a div when dragging an item from "sortable" and remove it once the dragging stops. Below is my JavaScript code: $(".sortableL ...