Search code examples
javascriptimageurlphoto

resize image with JavaScript


I have a webpage in which there is an image. I want to post this image on a blog with this script

<div id="container"></div>

<script>
var url = 'http://www. jpg';
var image = new Image();
image.src = url;
document.getElementById('container').appendChild(image);
</script>

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


Solution

  • Although it isn't quite clear to me what you're trying to accomplish exactly, it seems like there's little reason to use much JavaScript if all you're doing is including an image on your blog or website.

    You could get away with using simple HTML and CSS, if I understand your question correctly.

    <div id="container">
    <a href="linktowherever" target="_blank">
    <img src="linktoimage" style="width:50px;">
    </a>
    </div>
    

    Let the browser's renderer do the resizing.

    If you really must do this through JavaScript then you could recreate the above HTML like so;

    <script>
    var url = 'http://www. jpg';
    var image = new Image();
    image.src = url;
    image.style.width = "50px";
    var link = document.createElement("a");
    link.href = "linktowherever";
    link.target = '_blank';
    link.appendChild( image );
    document.getElementById('container').appendChild( link );
    </script>