The old HTMLImageElement.align property can still appear in legacy JavaScript, but it is deprecated. For new pages, use CSS such as float for left/right placement or vertical-align for inline vertical alignment.
image.align = 'right';
// Modern replacement for left/right placement
image.style.float = 'right';
align property Top ↑Older code used values such as left, right, top, middle, or bottom through the image's align property. Keep this knowledge when maintaining old pages, but avoid adding it to new markup.
const image = document.getElementById('i1');
image.align = 'right';
For the same left/right behavior shown by the original plus2net demo, update the element's CSS float value. CSS gives more predictable layout control and keeps presentation out of obsolete HTML attributes.
const image = document.getElementById('i1');
image.style.float = 'left';
// or
image.style.float = 'right';
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo of image alignment with JavaScript</title>
</head>
<body>
<img src="images/help.jpg" id="i1" alt="Help illustration">
<br><br><br><br>
<button type="button" id="align-left">Left</button>
<button type="button" id="align-right">Right</button>
<script>
const image = document.getElementById('i1');
const leftButton = document.getElementById('align-left');
const rightButton = document.getElementById('align-right');
function moveImage(side) {
image.style.float = side;
}
leftButton.addEventListener('click', () => moveImage('left'));
rightButton.addEventListener('click', () => moveImage('right'));
</script>
</body>
</html>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| name | 24-11-2014 |
| this is great method, thanks for your post, but i am using like this. img.src="captcha-demo.php?rand_number=" + (new Date()).getTime()); | |
| Kade | 25-11-2016 |
| Works great and uses minimal code. Thank you!! | |