Using the onclick event in JavaScript and HTML to transfer an image from one table to another

Currently, I have two tables set up. One table is filled with various images while the other table remains empty. My goal is to allow users to click on an image in the first table and have that specific image transferred over to the second table where it will be displayed at a larger size.

Here is how the structure of my tables appears:

<div>
        <table id="enlarged" width="530px" border="1">
            <tr>
                <th>Enlarged Picture.</th>
            </tr>
            <tr>
                <td>
                    <div id="div1"> </div>
                </td>
            </tr>   
    </div>

    <br/>
    <div>
        <table id="small" width="530px" border="1">
            <tr>
                <th>Click on picture to see it enlarged.</th>
            </tr>
            <tr>
                <td>
                    <img id="picture1" src="winter.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">
                    <img id="picture2" src="winter1.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">
                    <img id="picture3" src="winter2.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">
                    <img id="picture4" src="winter3.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">
                    <img id="picture5" src="winter4.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">
                </td>
            </tr>
        </table>
    </div>

In attempting this functionality, I created a JavaScript function like so:

function addPictureToTable(){

            var myPicture = document.getElementById("picture1");
            var table = document.getElementById("enlarged");

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            row.insertCell(0).innerHTML= myPicture;

        }

If needed, the images moved from the initial table can also be placed into a simple div rather than a separate table.

Answer №1

First and foremost, let's address what specific issue you are encountering with your current code. Next, consider making the elementID a parameter for your addPictureToTable function like so:

<img id="picture1" src="winter.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable();">

which can be updated to:

<img id="picture1" src="winter.jpg" style="height:100px; width:100px; align:left;" onclick="addPictureToTable("picture1");">

Transforming:

var myPicture = document.getElementById("picture1");

into:

var myPicture = document.getElementById(elID);

Moreover, it seems unnecessary to use table.insertRow(rowCount) unless you intend on continuously expanding the table upon each click. It may be more practical to obtain div1 by ID and then proceed with .innerHTML on that particular one.

Furthermore, consider eliminating the onClick event of the element inserted into the new div, along with potentially removing the element ID altogether. For simplicity, just insert an img tag in the div and set the src attribute of the "enlarged" image you wish to edit to match the src of the clicked image.

Upon reevaluating your code, it appears imperative to create a placeholder img tag with independent width/height attributes, altering only the src attribute dynamically (as currently, the height/width attributes from the source img are retained, resulting in a fixed size within the second table).

Answer №2

If you're looking for a cooler and more modern approach to your end-application, consider incorporating a face-box jQuery plugin. Check out these resources for some options:

You might find them useful!

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 binding v-on:change.native in the parent component of Vue.js

I have a component that includes a checkbox input: <template> <input id='one' type='checkbox' v-on:change.native="$emit('change')" /> </template> In another component, I am utilizing this component: &l ...

To display a sliding div at the bottom of the page, utilize the `.show` class with the CSS property `position: absolute; bottom: 0px;`. This

Currently, I am using jQuery's .hide function to conceal an "extra details" div located within a parent div. When the user hovers over the parent div, it is designed to appear using .show/.toggle with jQuery UI slide effect. However, I have encounter ...

The Discord bot seems to be stuck in time, relentlessly displaying the same start time without any updates in between. (Built with Node.js and Javascript

const Discord = require('discord.js'); const client = new Discord.Client(); var moment = require('moment'); const token = '//not telling you this'; const PREFIX = '!'; client.on('ready', () =>{ con ...

What is the best way to insert text into HTML through Javascript if there are no specific id names or classes within the tag?

I am looking to insert additional text into an anchor tag on my HTML page using JavaScript. The challenge is that there are no id, name, or class attributes within the anchor tag. Is there a workaround for this? A snippet of the code in question is provide ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

Column with a bottom aligned div

My current layout in Bootstrap 4 consists of four columns, but I am facing an issue where one of the columns with longer text is causing misalignment of the "buttons" at the end. https://i.sstatic.net/lWFgQ.png Below is the HTML code: < ...

Possible scope problem causing AngularJS image preview not showing up in ng-repeat loop

I came across this question and made some modifications. It works well when used outside of the ng-repeat. However, I'm facing issues when trying to use it within my repeat loop; the image.src does not update. I believe this is more related to the sc ...

Fix for - AttributeError: 'time' module does not have 'clock' attribute

I've been working on developing a ChatBot using a combination of HTML and Python. Despite using the latest version of Python (3.8), I encountered an error when trying to execute the form. I'm unsure why this error occurred since I made sure to us ...

Is it possible to rearrange an array by placing the items in positions determined by their property values

Here is an array example: let rawArray = [{ name: "Name", repeat: null }, { name: "Name1", repeat: 2 }, ...]; The requirement is to iterate through rawArray, check the repeat property, and if it's not null, duplicate that item bas ...

Stop Swiper Slide from moving when clicked on

I am currently utilizing Swiper JS and have encountered an issue. In my Swiper slider, each slide contains a button. Whenever I click on the slide or the button itself, the slide becomes the active one, causing the entire slider to move. Is there a way to ...

Positioning two labels within a Div container

Struggling to align two labels within a div using ASP.NET, where the length of the data displayed can vary. The challenge I'm facing is getting the first label to align to the left and the second label to the right. Since the data displayed is querie ...

Navigate through JSON data to add to an HTML table

HTML <table id="id_kbdata" cellspacing="0" cellpadding="0" > </table> JSON [ { "id":"3", "title":"Doing Business In...", "businessSubjectAreas":[ { "businessSubjectArea":"Market and Sell Products/Service" }, ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Send the randomly generated data to a jQuery function

After receiving data from the controller, I am displaying it in a JSP page using the following code snippet: <li> <a class="groupList" href="#" onclick="myfunction(${item.id})"> ${item.name} </a> </li> My goal now ...

Can different classes be assigned to each element in an HTML document?

Is there a way to assign unique classes to all elements in an HTML document or output within WordPress? This would make editing and styling the code much easier as each element would have its own distinct class. While I am aware that you can select classes ...

A guide on extracting all form fields with the maxlength attribute using JavaScript

Currently, I am utilizing html5 for the creation of my views and encountered an issue with the maxlength attribute in a few form fields. While maxlength is functioning correctly in desktop browsers, it seems to not be effective in android browsers. As a r ...

Is there a way to automate the clicking of a button on this webpage if using .click() is not effective?

Currently, I am developing an extension that facilitates purchasing products from Flipkart during flash sales. However, on the product page, I am unable to click the "Buy Now" button using JavaScript as it returns undefined. Here is the code for the Buy No ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

Replace the indexOf() method to be called on a null value

I have discovered a way to override functions in JavaScript, such as indexOf(), like this: var indexOf = String.prototype.indexOf; String.prototype.indexOf = function(){ //MY CUSTOM CODE HERE return indexOf.call(this, arguments); }; By doing this ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...