[javascript] Load image with jQuery and append it to the DOM

I'm trying to load an image from a given link

var imgPath = $(imgLink).attr('href');

and append it to the page, so I can insert it into a given element for an image viewer. Even though I searched Stackoverflow and the jQuery docs without end, I can't figure it out.

After I load the image, I want to set different values to it, like width, height, etc.

Update:

This is what I got. The problem I'm having is that I can't run jQuery functions on the img element.

function imagePostition(imgLink) {

// Load the image we want to display from the given <a> link       
// Load the image path form the link
var imgPath = $(imgLink).attr('href');

// Add image to html
$('<img src="'+ imgPath +'" class="original">').load(function() {

    $(imgLink).append(this);

    var img = this;

    // Resize the image to the window width
    // http://stackoverflow.com/questions/1143517/jquery-resizing-image

    var maxWidth = $(window).width();       // window width
    var maxHeight = $(window).height();     // window height
    var imgWidth = img.width;               // image width
    var imgHeight = img.height;             // image height
    var ratio = 0;                          // resize ration
    var topPosition = 0;                    // top image position
    var leftPostition = 0;                  // left image postiton

    // calculate image dimension

    if (imgWidth > maxWidth) {
        ratio = imgHeight / imgWidth;
        imgWidth = maxWidth;
        imgHeight = (maxWidth * ratio);
    }
    else if (imgHeight > maxHeight) {
        ratio = imgWidth / imgHeight;
        imgWidth = (maxHeight * ratio);
        imgHeight = maxHeight;
    }

    // calculate image position

    // check if the window is larger than the image
    // y position
    if(maxHeight > imgHeight) {
        topPosition = (maxHeight / 2) - (imgHeight / 2);
    }
    // x position
    if(maxWidth > imgWidth) {
        leftPostition = (maxWidth / 2) - (imgWidth / 2);
    }

    $(imgLink).append(img);

    // Set absolute image position
    img.css("top", topPosition);
    img.css("left", leftPostition);

    // Set image width and height
    img.attr('width', imgWidth);
    img.attr('height', imgHeight);  

    // Add backdrop
    $('body').prepend('<div id="backdrop"></div>');

    // Set backdrop size
    $("#backdrop").css("width", maxWidth);
    $("#backdrop").css("height", maxHeight);

    // reveal image
    img.animate({opacity: 1}, 100)
    img.show()

});

};

This question is related to javascript jquery image

The answer is


var img = new Image();

$(img).load(function(){

  $('.container').append($(this));

}).attr({

  src: someRemoteImage

}).error(function(){
  //do something if image cannot load
});

With jQuery 3.x use something like:

$('<img src="'+ imgPath +'">').on('load', function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

Here is the code I use when I want to preload images before appending them to the page.

It is also important to check if the image is already loaded from the cache (for IE).

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
        src: photoUrl
    });

    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {

        //image loaded:
        //your code here to insert image into page

    } else {
        //go fetch the image:
        $(imgPreload).load(function (response, status, xhr) {
            if (status == 'error') {

                //image could not be loaded:

            } else {

                //image loaded:
                //your code here to insert image into page

            }
        });
    }

I imagine that you define your image something like this:

<img id="image_portrait" src="" alt="chef etat"  width="120" height="135"  />

You can simply load/update image for this tag and chage/set atts (width,height):

var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);

after you get the image path, try either of following ways

  1. (as you need to set more attr than just the src) build the html and replace to the target region

    $('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
    
  2. you may need to add some delay if changing the "SRC" attr

    setTimeout(function(){///this function fire after 1ms delay
          $('#target_img_tag_id').attr('src',imgPaht);
    }, 1);
    

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?