Tips for increasing the number of pixels in the current position of an element?

I need to shift an image to the right by adding pixels to its current left position. The challenge arises when the image, positioned absolutely, goes back to its nearest relative parent (the container) and creates a strange visual effect.

Within my flex container, I have an image and a div both centered using the justify-content: center; property.

HTML code:

<button type="button" onclick="moveImage()">Move image</button>
<div id="container">
  <div id="left" class="block">Left</div>
  <div id="center" class="block">
    <img id="image" src="https://appharbor.com/assets/images/stackoverflow-logo.png" alt="stackoverflow">
  </div>
  <div id="right" class="block">Right</div>
</div>

CSS code:

html, body{
    width: 100%;
    height: 100%;
}

#container{
    display: flex;
    height: 100%;
}

.block{
    flex: 1;
}

#left{
    background-color: red;
}

#center{
    position: relative;
    display: flex;
    background-color: yellow;
    justify-content: center;
}

#right{
    background-color: orange;
}

#divCentered{
   width: 50%;
   height: 100px;
   background-color: brown;
}

Javascript code:

$( document ).ready(function() {
     var divParent = document.getElementById('center');
     var div = document.createElement("div");
     div.setAttribute("id", "divCentered");
     divParent.appendChild(div);
});

function moveImage(){
  $("#image").animate({
    left: "+=300px"
  }, 1000);  
}

Visit this JSFiddle link to see the issue with the image shifting behavior.

If you know a way to prevent the image from reverting to its parent and instead continue to add pixels in its current position, your advice would be greatly appreciated! Here's a big thanks in advance!

Answer №1

Finally, after numerous attempts, I have successfully found a solution to this issue.

By utilizing the .offset() method, I was able to obtain the position values of both the container and image with respect to the document.

To ensure correct positioning within the container, I set the left property of the image to 0, considering the container as the parent element.

Subsequently, by calculating the difference between the offsets of the container and the image, I determined the precise positioning of the image within its container, updating the left property accordingly.

Below is the code snippet that resolved the issue:

var leftCenterDiv = $("#center").offset().left;
var leftImage = $("#image").offset().left;

$("#image").css("left", 0);
$("#image").css("left", leftImage - leftCenterDiv);

For reference, here is the revised version on JSFiddle.

Answer №2

Set the image to have an exact horizontal starting point:

#image {
  position: absolute;
  z-index: 2;
  height: 50px;
  width: 100px;
  left: 45px;
}

Answer №3

Make sure to maintain the initial image position by keeping it unchanged even when adding pixels, for example, left:45px

. If you need to add pixels without shifting the position, you can use the
!important` property on the left attribute.

#image {
  position: absolute;
  z-index: 2;
  height: 50px;
  width: 100px;
  left: 45px !important;
}

Check out the Jsfiddle demo here

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

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Modifying the date formatting in JavaScript if it is incorrect

Recently, I developed a mobile application that can scan QR-CODEs containing various information, including a date. However, there have been changes in the format of the date within the QR-CODE between previous and new versions. Previously, the date was fo ...

Looking for a way to integrate a Facebook feed (RSS) into your webpage? Try using this jQuery

I am looking for a quick and easy way to display a Facebook feed (including posts, comments, and images if possible) on a website without using the standard 'like box' provided by Facebook. After some research, I came across this option: Are th ...

An asynchronized code block processes an array of multiple Ajax deferred calls, concluding with a synchronous final code block

I am new to the world of jQuery and AJAX and I'm currently exploring how deferrals and promises can help me solve a particular issue. Here's what I'm trying to achieve: I want to make calls to multiple URLs, process the returned results in p ...

What could be causing my grid-area properties to not take effect?

I'm attempting to create a basic structure with a header in the top row, menu and content in the middle row, and footer at the bottom. Here is what I have so far: body { color: white; } .container { background: cyan; display: grid; ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

Next.js optimizes the page loading process by preloading every function on the page as soon as it loads, rather than waiting for them to

My functions are all loading onload three times instead of when they should be called. The most frustrating issue is with an onClick event of a button, where it is supposed to open a new page but instead opens multiple new pages in a loop. This creates a c ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Is there a way to trigger a function with ng-click in my AngularJS directive?

I am struggling to understand how to invoke a function from my directive using ng-click. Here is an example of my HTML: <div> <directive-name data="example"> <button class=btn btn-primary type="submit" ng-click="search()"> ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

Setting bootstrap datetimepicker values dynamically from a variable

I'm trying to utilize the inline bootstrap datetimepicker from At the moment, it opens in a popup window after the user selects a date/time from a table on another page. My goal is to pass the date/time from that page into datetimepicker and have it ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Video background in webflow not currently randomizing

I want to add a dynamic video background to my website created with Webflow. I attempted to achieve this using Javascript by including the following links: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70fed ...

Why are all links broken and the mobile menu disappeared after installing featherbox gallery?

If you want to see for yourself, here is the link. I can't figure out why my website has suddenly lost functionality on this specific page. None of the links work, except for the home and contact (the non-expandable ones). The navigation menu seems ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

Storing JSON data as a string within JSON format with the help of PHP

When conducting testing, I am looking to utilize Ajax for requesting JSON data from the server. The JSON format that Ajax should receive appears as follows: json=[ {"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}, {"source":"pa","json ...

Can a stroke in an SVG image be created using a gradient color?

Is it possible to create a gradient in the stroke color of these two lines, currently set to #389967, within this SVG? .chart-three svg .circle-foreground { stroke: #389967; stroke-dasharray: 494.55px 549.5px; stroke-dashoffset: 494.55px; stroke- ...