Copy link to clipboard
Copied
Hello,
I need to set dynamically (by click or whatever) the "top and left" value of this object defined in the section "style" :
<style>
#MyObject{
width: 15%; top: 500px; left: 1200px;
height: 100px;
background-image: url(http://MyObject.png);
background-size: cover;
background-repeat: no-repeat;
position: absolute;
}
</style>
Is it possible? If yes how?
Thanks.
You can do that dynamically via a couple of text input boxes, example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Set Position</title>
<style>
#MyObject{
width: 15%;
top: 300px;
left: 100px;
height: 100px;
background-image: url(http://MyObject.png);
background-size: cover;
background-repeat: no-repeat;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<input type="text" class="topPosition" placeholder="Top Position">
<input type=
...
Copy link to clipboard
Copied
I don't understand the question or why you're using absolute positioning for any of this. Positioning is not recommended in primary layouts. Please post a URL to your online site so we can see exactly what's going on.
Copy link to clipboard
Copied
You can do that dynamically via a couple of text input boxes, example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Set Position</title>
<style>
#MyObject{
width: 15%;
top: 300px;
left: 100px;
height: 100px;
background-image: url(http://MyObject.png);
background-size: cover;
background-repeat: no-repeat;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<input type="text" class="topPosition" placeholder="Top Position">
<input type="text" class="leftPosition" placeholder="Left Position">
<input type="submit" class="setPosition" value="Set Position">
<div id="MyObject"></div>
<script>
const topPosition = document.querySelector('.topPosition');
const leftPosition = document.querySelector('.leftPosition');
const myObject = document.getElementById('MyObject')
const setPosition = document.querySelector('.setPosition')
setPosition.onclick = function() {
let getTopPosition = topPosition.value;
let getLeftPosition = leftPosition.value;
myObject.style.top = getTopPosition + 'px';
myObject.style.left = getLeftPosition + 'px';
}
</script>
</body>
</html>
Copy link to clipboard
Copied
Thank you both Nancy and Osgood for the reply.
The solution of Osgood work for me!