Ways to swap out an img element with an almost identical gif element while maintaining its precise placement consistently

I am facing an issue in my code where a random element is generated within the body and when clicked, it is replaced with another gif element. I am using offset() to obtain the top and left values of the original image, and then using replaceWith() to swap it with the gif. Additionally, I use css() to set the left and top values of the gif like this:

function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

var thewidth = randomInt(1,1000);

$("body").prepend( "<img src='red_dot.png' class='enemies' id='enemy' left:thewidth/2 + 'px'></img>");

var n = $("#enemy").offset();
    console.log(n.left);
    console.log(n.top);
    $("#enemy").click(function()
    {
      $("#enemy").replaceWith("<img src='explosion.gif' id = 'explosion'></img>");
      $("#explosion").css({"left" : n.left+'px', "top" : n.top + "px"});
.enemies
{
  position: fixed;
  transform: scale(0.01,0.01);
}

#explosion
{
  transform: scale(0.1,0.1);
  position: fixed;
}

Although the top and left values are the same for both elements, they appear at different positions when the code is executed. I am unsure why this happens and how I can ensure that the gif always replaces the image at its exact position. Can anyone provide insights into this issue?

Answer №1

html is missing the style attribute in the <img> tag, which is self-closing. To set the width using the calc() function in the left property value, and then replace the element with the same value in the .replaceWith() call.

Another approach is to use jQuery() as recommended by @GeneParcellano to replace the src and id attributes of the same element using .attr(). You can also chain .removeClass() to remove the "enemies" class name from the element.

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

var thewidth = randomInt(1, 1000);

$("body")
.prepend(
  $("<img />", { 
    src :"http://lorempixel.com/50/50/cats",
    "class": "enemies",
    id:"enemy",
    css: {
      left: "calc(" + thewidth / 2 + "px)"
    }})
  );

$("#enemy").click(function() {
  $(this)
  .attr({
     "src": "http://lorempixel.com/50/50/nature"
  ,  "id": "explosion"
  })
  .removeClass("enemies");
});
.enemies {
  position: fixed;
  /*transform: scale(0.01, 0.01);*/
}
#explosion {
  /*transform: scale(0.1, 0.1);*/
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

jsfiddle https://jsfiddle.net/jK5m1y1L/3/

Answer №2

Adjust the transform origin property within the enemies class to position the image's origin at the top instead of the center.

.enemies{
 transform-origin: 0% 0%;
}

Make sure to also apply this in the CSS properties for the explosion id.

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

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

Modifying the border of images in a Weebly gallery

I'm having trouble changing the gallery image borders on Weebly. The client prefers using Weebly for easy backend editing once the design is in place, so I need to work within these parameters. Usually, I can make most code edits easily...but this iss ...

Hold off on running the code until the image from the AJAX request is fully loaded and

Currently, I am facing a challenge with my code that aims to determine the width and height of a div only after it has been loaded with an image from an AJAX request. The dimensions of the div remain 0x0 until the image is successfully placed inside it, c ...

Is the image overlay experiencing a flickering issue?

Last time, none of the solutions seemed to work quite right with the project, so let me try asking the question in a slightly different way this time. Basically, I have an image that, when someone hovers their mouse cursor over it, a div appears (containi ...

IN to CM Conversion Size Chart

I'm just starting out and I want to make a size chart table that can convert between metric units. For example, I have table data with values in "inches" and I want to be able to switch it to "centimeters" with the click of a button. Some of the data ...

Customizing CSS for Internet Explorer browsers

I am looking to target specific CSS styles for Internet Explorer only, without affecting other browsers. Initially, I tried using conditional comments: <!--[if lt IE 7 ]><html class="ie6 ie"> <![endif]--> <!--[if IE 7 ]><html cl ...

JQuery If Statement always outputs a consistent number regardless of the input provided

I'm facing an issue with my HTML form and JQuery code that is supposed to calculate a figure. The problem I am encountering is that the if statement always returns the same number, regardless of the input: $(document).ready(function() { ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

Steps for displaying a bootstrap modal in alignment with the triggering button's position

Recently diving into the world of bootstrap and AngularJs has been quite the learning experience for me. One challenge I encountered was trying to implement a bootstrap modal dialog box to show additional details within a table column. My goal was to hav ...

There is a missing template at the specified location: index.html in Django

Hello, I recently created a new project and placed the index.html file in the templates directory. However, when I run the server, I encountered an error message stating TemplateDoesNotExist at /. Can anyone point out what mistake I might have made? Below ...

PHP's Encoding Woes Are Back in Action

I'm encountering encoding challenges on my website, and it's becoming quite frustrating. Allow me to elaborate My meta tag specifies utf8 as the charset. The scripts I'm using also have utf8 defined (<script type="text/javascript src=". ...

The error message for an onclick event in HTML/JavaScript references a ReferenceError, and also involves issues with

Currently, I am working on creating a simple text-based golf game as a coding exercise. This game does not involve any trigonometry; instead, it relies on randomness to determine how hard the ball is hit and how many shots are required to reach the hole. A ...

The panel's fullscreen feature crashes when exiting after triggering the 'resize' function

I'm facing an issue with a popup window that automatically goes into fullscreen mode. There are two buttons - one to exit fullscreen and another to simply close the window. When the window is in fullscreen, the exit button works perfectly. However, i ...

The carousel top position in Bootstrap 4 is not functioning properly

I am struggling to get the teal rectangle to move to the top of the carousel. I have set my carousel to have a position relative and my teal rectangle to have a position absolute with top="0", but it doesn't seem to be working properly. Instead of mov ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

What is the correct way to set up Cypress intercepts within a beforeEach function?

As a newcomer to Cypress, I find some aspects of it challenging despite its apparent simplicity. I am facing a specific issue: const componentsRouteMatcher = { pathname: '/component-management/api/components', query: { size: &apos ...

Having difficulty retrieving an angular file from a location outside of the asset folder

I'm encountering issues with a small project that is meant to read a log and present it in table format. Here is the outline of the project structure: project structure Within the LOG directory, I should be able to access motore.log from my DataServi ...

Transfer data from a Django template populated with items from a forloop using Ajax to a Django view

Struggling to implement a click and populate div with ajax in my django e-commerce app. The function involves clicking on a category in the men's page which then populates another div. gender.html {%for cate in cat%} <a href="javascript:getcat()" ...

When I press the button, a model popup will display the complete information

How can I display full information on a model popup when clicking a button? <button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal" > <i class="glyphicon glyphicon-zoom-in"></i> </button>< ...