How can I resize an image with JavaScript

I’m new to web development.
I have a webpage in PHP in which there is an image.
I want to post this photo on a blog with this script

<div id="x"></div>

<script>
var img = document.createElement("img");
img.src = "http://www.meteoarachova.com/stickersPWS/sticker.php";
var src = document.getElementById("x");
src.appendChild(img);
</script>

how can I resize the image and put a link for the blog visitor to return to the image page?

16 thoughts on “How can I resize an image with JavaScript”

  1. Resize the image using el.style.width = 50%; and img.style.height = 50%; this will resize the images width and height by 50%. You can also use pixels or other size increments in CSS using el.style.width/height.

    As for creating a link, if you want to use the image as a link, you could create an a tag and wrap it around the image controlling the size of image in that element. Then add the href attribute pointing to the page you wish to open when the user clicks the image.

    let div = document.getElementById("x");
    
    let aTag = document.createElement("a");
    aTag.href = 'http://www.meteoarachova.com/stickersPWS/sticker.php';
    aTag.title = 'click to open image';
    aTag.target = '_blank';
    aTag.outline = 'none';
    
    let img = document.createElement("img");
    img.src = "http://www.meteoarachova.com/stickersPWS/sticker.php";
    img.style.width = '40%';
    img.style.height = '40%';
    
    aTag.append(img)
    div.append(aTag);
    
    console.log(document.getElementsByTagName('a')[0])
    <div id="x"></div>
    Reply

Leave a Comment