October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Embed, Resize, and Crop Images with jQuery

Use jQuery to insert images and change their attributes, CSS for display sizing and cropping, and canvas for pixel-level image edits.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use jQuery to add an <img> element, change its attributes, or control how it looks with CSS. For an actual pixel-level crop or a newly exported image, draw the loaded image into a canvas; changing CSS does not alter the source file.

Add an image with jQuery

An <img> element embeds an image in the page. Create it with jQuery, set its attributes with .attr(), then insert it into a container with .append():

As an Amazon Associate I earn from qualifying purchases.

<div id="gallery"></div>

<script>
const $image = $("<img>").attr({
  src: "/images/landscape.jpg",
  alt: "Snow-covered ridge at sunrise",
  width: 1200,
  height: 800
});

$("#gallery").append($image);
</script>

The example assumes jQuery is already loaded. Use meaningful alt text when the image conveys information. If it is purely decorative, use alt="". Setting intrinsic width and height lets the browser reserve the correct aspect ratio before the image loads. See the jQuery .attr() documentation, jQuery .append() documentation, and MDN’s <img> reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set attributes through jQuery or DOM APIs rather than concatenating untrusted input into an HTML string. This avoids treating user-controlled values as markup.

#1 Best Overall
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Change an existing image’s source

To replace an image, update its src and, when appropriate, its alternative text together:

$("#preview").attr({
  src: "/images/alternate.jpg",
  alt: "Description of the alternate image"
});

Changing src schedules a resource fetch; it does not mean the new image is ready immediately. If later code needs to draw the image into a canvas, wait for its load event and handle a failed load before drawing.

Resize or crop an image’s display with CSS

For a responsive image that scales within its container without distorting its proportions, apply CSS. jQuery’s .css() can set presentation properties, though a stylesheet is often easier to maintain:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
JavaScript and jQuery: Interactive Front-End Web Development
  • JavaScript Jquery
  • Introduces core programming concepts in JavaScript and jQuery
  • Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$("#preview").css({
  maxWidth: "100%",
  height: "auto"
});

To fill a fixed-size box and crop the visible display, use object-fit: cover. object-position controls which area stays visible:

$("#preview").css({
  width: "320px",
  height: "200px",
  objectFit: "cover",
  objectPosition: "center"
});

These are visual changes only. They do not modify the downloaded bitmap or generate a cropped image file. For details on jQuery styling, see the jQuery .css() documentation.

Choose the right approach for responsive images

jQuery can set image attributes, but it is not a replacement for the browser’s responsive-image selection features. Use srcset and sizes to offer image candidates and describe the rendered width, or use <picture> when source selection needs to vary by conditions such as format or layout.

<img
  src="/images/landscape-800.jpg"
  srcset="/images/landscape-400.jpg 400w, /images/landscape-800.jpg 800w, /images/landscape-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 800px"
  width="1200"
  height="800"
  alt="Snow-covered ridge at sunrise">

The browser uses the candidates and sizes information to choose an appropriate resource; src remains a fallback. Do not mix width (w) and density (x) descriptors in one srcset. For offscreen images, loading="lazy" lets the browser defer loading at its discretion. Avoid lazy-loading a likely above-the-fold lead image. Keep intrinsic dimensions so layout space can be calculated while an image is loading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Alternative text should communicate an informative image’s purpose. A title attribute is not a substitute for necessary visible text or alternative text; users may not encounter its tooltip.

Crop pixels or create a new image with canvas

For a real crop, resized bitmap, or exported result, wait for the image to load and use the browser’s canvas API. drawImage() has forms for drawing at a position, scaling, and selecting a source rectangle. This example draws the full image into a smaller canvas, scaling it to fit:

const image = document.querySelector("#preview");
const canvas = document.querySelector("#result");
const context = canvas.getContext("2d");

function drawResizedImage() {
  const width = 400;
  const height = 267;
  canvas.width = width;
  canvas.height = height;
  context.drawImage(image, 0, 0, width, height);
}

if (image.complete && image.naturalWidth > 0) {
  drawResizedImage();
} else {
  image.addEventListener("load", drawResizedImage, { once: true });
  image.addEventListener("error", () => {
    console.error("The image could not be loaded.");
  }, { once: true });
}

For cropping, use the drawImage() form that accepts a source rectangle as well as a destination rectangle: the source rectangle identifies the portion of the loaded image to copy, and the destination rectangle sets its position and size on the canvas. Consult MDN’s Canvas tutorial on using images for the available argument forms and export details.

Canvas pixel access and export have origin-clean restrictions. A same-origin image can be processed subject to the page’s normal loading rules. For a remote image, the server must allow the requesting origin through CORS. Setting the image’s crossorigin attribute alone cannot make a server grant that permission. If the server does not permit the request, canvas pixel reading or export can fail.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common image problems

  • The image does not appear: Check that the URL in src is correct and that the resource loads successfully. Attach an error handler when code depends on the result.
  • The canvas is blank or drawing happens too early: Wait for the image’s load event before calling drawImage(); handle error as well. If the image may already be cached, check complete and naturalWidth before waiting.
  • Canvas export or pixel access is blocked for a remote image: The remote server must send appropriate CORS permission. The client cannot override a server that does not allow the requesting origin.
  • The image looks cropped, but the saved file is unchanged: object-fit changes only the displayed result. Draw the intended source rectangle into a canvas to create a pixel-level crop.
  • The page shifts when the image arrives: Provide correct intrinsic width and height values so the browser can reserve space.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a website image rather than build image behavior into your page, ScreenshotNeo returns a screenshot or PDF from one GET request. Cookie banners, popups, and chat widgets are removed before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for request options. Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Does jQuery edit an image file when I change its CSS?

No. CSS changes how the image is displayed; canvas is the browser option for creating a pixel-level result.

Can I use a remote image in canvas?

Yes, when the remote server permits the requesting origin through CORS. The `crossorigin` attribute cannot grant that permission by itself.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

SaleBestseller No. 1
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05
SaleBestseller No. 2
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript Jquery; Introduces core programming concepts in JavaScript and jQuery; Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$22.28

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.