Guide on positioning an image in the upper right corner of another

Does anyone know how to use JavaScript to display one image in the top right corner of another image?

I attempted to achieve this by using the appendChild() method to add the image element, but it doesn't seem to be working.

function appendImage(element, src, alt)   
{    
  var image = new Image();    
  image.src = src;    
  image.alt = alt;    
  element.appendChild(image);    
  return false;    
}

<img border="0" src="www.gravatar.com/avatar/" alt="" width="70" height="70"     
onclick="appendImage(this, 'cancel3.png', 'Picture of foo')";>

Any ideas on what I might be doing wrong?

Answer №1

It is not possible to "append an image to another." In HTML, it is invalid to place another element inside an <img> tag as the <img> tag cannot have children or a closing tag.

If you want to layer one image on top of another, you can replace the original image with a div of the same size and include both images inside it. By absolutely positioning the second image over the first one, you can achieve this effect. Below is a modified version of your function that demonstrates how to do this:

function overlayImage(element, src, alt) {
   var
      div = document.createElement('div'),
      img = new Image();
   element.parentElement.insertBefore(div, element); // add the div to the parent
   div.style.display = 'inline-block'; // make it behave like an image
   div.style.position = 'relative'; // for absolute position of children
   div.appendChild(element);
   img.src = src;
   img.alt = alt;
   img.style.position = 'absolute';
   img.style.right = 0;
   img.style.top = 0;
   div.appendChild(img);
}

Here is a solution for achieving the desired result!

Check out a Live Demo at JsFiddle

Instead of just using a single <img src="(base)"> tag, this approach replaces it with the following structure.

<div style="display:inline-block; position:relative;">
   <img src="(base)">
   <img src="(overlay)" style="position:absolute; top:0; right:0;">
</div>

If you have control over the page, it would be beneficial to create a CSS style that can be applied universally instead of manually adjusting each element. Additionally, if you need to apply this technique to numerous images, consider pre-creating the structure mentioned above rather than dynamically modifying it with JavaScript post-page load.

Answer №2

What is your motivation for using Javascript in this scenario?

An alternative solution involves utilizing CSS:

HTML:
<img id="bg-image" src="background.jpg"/>
<img id="fg-image" src="foreground.jpg"/>

CSS:
#fg-image{
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}

If the intention is to perform an action on click (such as switching the images), you can achieve it like so:

HTML:
<img id="fg-image" src="image.png" onclick="performAction()"/>

JavaScript:
function performAction(){
  window.alert("Action performed!");
}

Answer №3

You cannot simply attach one image to another image. The recommended approach is to use an HTML structure similar to the following:

<div id="wrapper"
     style="position: relative; width: 80px; height: 80px"
     onclick="attachImage(this, 'cancel3.png', 'Picture of bar')">

     <img border="0" src="www.gravatar.com/avatar/" alt="" />

</div>

Answer №4

To create a wrapper for two images, you can utilize a div. The first image covers the entire area of the div, while the second image is positioned at the top right corner of the same div. These two images are considered siblings rather than parent-child elements.

function addImage(container, src, alt) {
  var img = new Image();
  img.src = src;
  img.alt = alt;
  img.style.position = "absolute";
  img.style.right = 0;
  container.appendChild(img);
  return false;
}

document.getElementById("wrapper").onclick = function() {
  addImage(this, 'http://placekitten.com/40/40', 'Foo Picture');
};
#wrapper {
  display:inline;
  position:relative;
}
Click on the image!
<div id="wrapper">
  <img border="1" src="http://placekitten.com/100/100" width="100" height="100">
</div>

Answer №5

Are you referring to Javascript? If so, I believe your image identifier is myImage.

var img = document.getElementById(myImage).style;
img.position = "absolute";
img.top = "0px";
img.right = "0px";

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

Guide to positioning a rectangular shape within a QML Pane

When working with this code, focus on the pink box outlined in blue and the blue box inside it. https://i.sstatic.net/NH8YS.png I'm looking to position the blue Rectangle to the right of the pink box. How can this be achieved? Why are the anchors no ...

The AngularJS ng-if directive functions on a variable will only function on the

I'm currently working on updating an old codebase that was written in AngularJS, a framework I am not very familiar with. My task is to implement a spinner that appears when an HTTP request is sent and disappears once the response is received. The sp ...

Creating a PDF of a dynamic PHP webpage

Currently, I'm working on developing a customized invoicing application that uses PHP and MySQL to create interactive invoices directly in the web browser. The design includes tables and CSS to enhance the layout. I have a concept in mind to improve ...

What is the best way to send an array and file in the same AJAX request?

When attempting to send both an image file and an array through my AJAX request to a PHP script, I encountered an issue where either the array or the image file doesn't appear. The problem seems to stem from the specific lines that need to be added to ...

I'm experiencing difficulties in installing dependencies for my project through npm, as it keeps showing an error

Recently, I decided to delve into the world of HTML5 and javascript games by running a browser game from Github. The game that caught my eye is called BrowserQuest, and you can find it on Github. A hiccup arose while using npm debug: 237 error 404 Not ...

Other Components take turns submitting the form in one Component

Two components, CreateCandidate and Technologies are being used. CreateCandidate requires technologies from the Technologies Component. When passing the technologies to CreateCandidate, the form within CreateCandidate is submitted. Below is the code: Crea ...

"Implement a 'Show More/Show Less' Button Functionality for Various Content Using

I'm having trouble implementing a JavaScript solution that adds read more/less buttons to my testimonials. The issue is that it only seems to work for one button and not multiple as I had hoped. Is there a way to modify this code so that it can be use ...

JavaScript image element loaded but still has a height of 0

This particular issue is causing frustration as it seems to only work with a specific set of images and not with others. The object in question is: function PreLoader(toLoad, parent, images) { var errored = 0; var loaded = 0; var toLoad = toLoad; ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

The datatable does not adjust to changes in page size

My jsfiddle example showcases different card boxes, and I am currently focusing on making the 'Table 1' box responsive. However, I have encountered an issue: Check out my jsfiddle example here code If you open the jsfiddle with a large enough ...

Creating dynamic dropdown menus in React JS through conditions

I'm currently working on a Dnd Character Sheet builder and I need to implement 6 dropdowns for the main stats. Each dropdown should have options from an array of values [8,10,12,13,14,15]. However, once a number is selected in one dropdown, it should ...

Vue Service - 401 (Access Denied)

Whenever I attempt to execute the "getUserData" method, it results in a 401 (Unauthorized) error. Strangely enough, when I make a GET request to the URL "" with the same headers in Postman, it works perfectly fine! How can I properly set my request heade ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...

What is the best way to target a nested selector in CSS?

To ensure the entire cell is filled when a modal is present, the padding of the table should be zero. See image https://i.sstatic.net/Qq2T4.png How can I target the specific selector nested within the table under different classes and IDs? I've expe ...

Inquiries about filesystem operations in Node.js

Goal The objective is to determine the completion of file writing using either fs.writeFileSync() or fs.writeFile(), in order to trigger another function. Context Currently, I am utilizing fs to write files. After consulting the documentation at: htt ...

Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows: <ul class="page-sidebar-menu"> <li class="menu"> <a href=""> <span class="title">Menu Item</span> <span class="arrow"></span> < ...

Generating HTML elements on the server-side vs. retrieving data as JSON and dynamically creating elements using JavaScript

Looking to implement an AJAX search feature that will retrieve and display topics from a forum, including just the topic link and subject. My question is: Which method would be more efficient and quicker? Retrieve the threads list as a JSON string, co ...

Web page experiencing "increased magnification during loading"

I've been experiencing an issue with my mobile site where the page loads as if it's zoomed in every time. I can easily scale it on a touch phone to make it look right, but I'm looking for ideas on how to prevent this from happening altogethe ...

The form in popover is experiencing issues with jQuery functionality

I need assistance with setting up a form inside a popover that utilizes jQuery and Ajax for form submission with calculations. However, I am facing issues as jQuery seems to not be functioning properly. My project is based on Ruby on Rails. This is the co ...