JavaScript: Update the object's style.left property by modifying the value of x

My current scenario is as follows:

I have a div with a CSS property of `left:10px;`. All div elements have their positions set to fixed. I store this value in a variable using JavaScript:

var Left = document.getElementById("div").style.left;

By alerting the variable Left, I receive a message displaying "10px". You can view this example on JSFiddle here: http://jsfiddle.net/L19rq2tk/2/

Now, my goal is to update the position value using the variable Left. I have tried various approaches, but none seem to work:

Left = "100px"; --> does not work
Left = 100px;   --> does not work
Left = "100";   --> does not work
Left = 100;     --> does not work

Fortunately, I found that I can successfully change the position by directly targeting the element:

document.getElementById("div").style.left = "100px";

If anyone has any advice or solutions to this dilemma, it would be greatly appreciated!

Answer №1

left is compatible with position:absolute
Check out the latest fiddle here
Newly Revised

When you add position, whether it's relative or absolute, it will get the job done. Adding position:absoute could potentially have some negative effects on your design(as mentioned by Ionic in the comment)
See the demonstration

Answer №2

To effectively implement the explicit form you mentioned in your response, utilize

document.getElementById("div").style.left = "100px";
. If your goal is to optimize performance by minimizing element lookups, consider employing the following approach:

var savedStyle = document.getElementById("div").style;
savedStyle.left = '100px';

The reason why the method you are attempting doesn't work as expected is that Left creates a new copy of the value instead of referencing the existing one. Modifying the Left property only alters the stored value, not the original value that object.style.left holds. Although multiple variables can point to the same object, they cannot point to the same value simultaneously. You can observe this concept with an illustrative snippet demonstrating the distinction.

var x = 1;
var y = x;
document.write('x = ' + x + '<br>');
document.write('y = ' + y + '<br>');
document.write('Updating y to 2<br>');
y = 2;
document.write('x now equals = ' + x + '<br>');
document.write('y now equals = ' + y + '<br>');

var xObj = { myValue: 3 };
var yObj = xObj;
document.write('xObj.myValue = ' + xObj.myValue + '<br>');
document.write('yObj.myValue = ' + yObj.myValue + '<br>');
document.write('Changing yObj.myValue to 1<br>');
yObj.myValue = 1;
document.write('xObj.myValue is now = ' + xObj.myValue + '<br>');
document.write('yObj.myValue is now = ' + yObj.myValue + '<br>');

Answer №3

Check out this code example.

You set the size to 100px, but forgot to include position:relative or position:absolute. As a result, nothing is visible on the screen because it's being placed in the background.

Answer №4

By setting the value to the variable left, nothing will happen. You must assign the value to the HTML element.

Try this:

document.getElementById("div").style.left="100px";

"left" is a variable that only retains the previous value.

Additionally, you need to specify

position: relative

for your div so it can move. The left, top, and other position CSS properties can only take effect if the element has a position property, which was missing in yours.

http://jsfiddle.net/L19rq2tk/

Here is the updated fiddle for you;

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 correct way to effectively refresh an included PHP file?

As a novice in the programming world, I've encountered yet another challenge that I hope you can assist me with. Here is the HTML code I'm currently working with: <div class='hold'><?php include 'image.php'; ?>< ...

Create a typing effect in Javascript that mimics the user's input

Trying to simulate a typing effect with the sentence extracted from user input using JavaScript, but encountering some issues. Successfully capturing and displaying the input in the console with console.log(), however, incorporating the typing effect func ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

"Unfortunately, Azure Web Static Apps do not have the capability to access .env files that are prefixed with NEXT

Suppose I have an .env file set up like this: NEXT_PUBLIC_API_BASE_PATH = value1 While this .env is functioning correctly in my local environment, once deployed to Azure Web Static Apps and added to the configurationhttps://i.sstatic.net/eqiYn.png My app ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Implementing default header and footer with Angular's ui.router

When dealing with ui.router modules, I have identified three different methods for setting a default header and footer for every view: DEFAULT HEADER <CONTENT> DEFAULT FOOTER 1. Using ng-include - inserting your header/footer in the initial .html ...

Can dependency injection be implemented while utilizing the new operator?

My goal is to incorporate a strategy pattern into my program. Specifically, I want to be able to determine at runtime which class to create an instance of. Implementing this may seem straightforward at first: if(...) { this.service = new ServiceA(); } el ...

The jQuery fade speed effect has a limitation where it can only be utilized

When a specific link is clicked, I want a div to display with a fadeIn effect and then fadeOut when the link is clicked again. However, after the first click following an HTTP request, the fadeIn works but the fadeOut does not (the div closes though). More ...

Alert and console.log continue to show the error message: 'Uncaught TypeError: Cannot read property ' ' of undefined

Encountering a Uncaught TypeError: Cannot read property 'valeurs' of undefined, however the alert() and console.log() functions are successfully displaying the data. Below is the code snippet: var item = document.getElementById('inputData&a ...

Trouble getting SVG line to display within Bootstrap 4 flex divs

I am attempting to establish a connection between the first two circular div elements using an SVG line. While inspecting, I can visualize the line but it remains hidden on the page. I tried adjusting the z-index without success. However, increasing the wi ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

tips for ensuring uniform height on responsive thumbnails

Can someone help me figure out why this code isn't working on my page? var gallery = $('.photos').gallerify({ margin:10, mode:{ maxHeight: screen.height * 0.5, breakPoints:[ { minWidth: 1170, columns: 4, }, { minWidth: 970, col ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

How do I ensure the CSS triangles maintain their correct boundaries when hovered over with the cursor?

Can the issue of incorrect triangle activation be fixed when hovering on http://jsfiddle.net/2AXhR/? Sometimes the wrong triangle is triggered due to the triangles' bounding areas being rectangles, causing overlap and z-index conflicts. <style ...

CSS: selecting the adjacent siblings of a certain class, starting from the first and

I am working on achieving the following goal: https://i.sstatic.net/xHoIG.png Elements containing values should have a gray 'ribbon'. Elements with values are given a class selected, while elements without any value do not have this class. Thi ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

Troubleshooting lack of error responses from Backend RestAPI with Axios

I am currently facing an issue with receiving a response from my backend system (Node.js Express RestAPI). exports.send = function(req, res) { console.log("sent function running!") let contact = new Contact(req.body) contact.send() ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...