Adjust the height of an image based on the width of the viewport to create a

Is there a way to dynamically adjust the height of an image using jQuery based on the width of the viewport?

For example,

If the website width is 450px, I would like to change the image width from 300 to 100.

I am currently using timthumb to resize my images.

Here is the HTML code:

<img src="timthumb.php?src=myimage.jpg&amp;h=300&amp;w=750&amp;q=100" class="MyImages">

How can I achieve this using jQuery?

Answer №1

This solution should work effectively. Just ensure to add the src attribute after jQuery captures the viewport width and remember to update it whenever the window is resized.

<img id="img1" src="" class="MyImages">
<script type="text/javascript">
$(function() {
  update_image();
  $( window ).resize(function() {
    update_image();
  });
});
function update_image(){
  var width = $( window ).width();
  if(width<450) { var picwidth=100; } else { var picwidth=300; }
  $('#img1').attr('src','timthumb.php?src=myimage.jpg&h=300w='+picwidth+'&q=100');
}
</script> 

To address your query: Modify your image elements as shown below:

<img src="" class="MyImages" data-src="myimage.jpg">

By using jQuery, you can now retrieve the correct sizes for your images:

<script type="text/javascript">
$(function() {
  $('img').each(function(){
    update_image(this);
  });
  $( window ).resize(function() {
    $('img').each(function(){
      update_image(this);
    });
  });
});
function update_image(e){
  var width = $( window ).width();
  if(width<450) { var picheight=100; } else { var picheight=300; }
  var image = $(e).attr('data-src');
  $(e).attr('src','timthumb.php?src='+image+'&h='+picheight+'&q=100');
}
</script> 

Implementing this will ensure that all your images are dynamically updated when resizing the viewport.

Answer №2

To ensure compatibility with modern browsers that support CSS3, you can utilize CSS3 media queries without worrying about older browsers like IE7.

For example:

@media (max-width: 450px) {
    .MyImages{width:100px;}
}

If you prefer a solution using pure JavaScript/jQuery:

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

$(function(){
   if(viewport().width<=450){
     $(".MyImages").css("width":"100px");
   }
});

If you want to ensure that the solution works even when the browser is resized:

$(window).on("resize",function(){
   if(viewport().width<=450){
     $(".MyImages").css("width":"100px");
   }
});

Keep in mind: Using JavaScript might be more resource-intensive compared to the CSS3 approach on some browsers.

Answer №3

You can achieve this without relying on jQuery. Simply specify the desired width and height properties for your image:

<img src="myimage.jpg" id="varimage" width="100" height="200>

....

var img = getElementById("varimage");
img.height = 400;
img.width = 200;

If you prefer to use jQuery (even though it's not necessary in this case):

$("#varimage").width(400);
$("#varimage").height(200);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to configuring eslint-webpack-plugin rules in Webpack

How can I properly configure options for the Eslint plugin with Webpack? This is what my webpack.config.js file looks like: const path = require('path'); const ESLintPlugin = require('eslint-webpack-plugin'); module.exports = { plu ...

Attaching the CSS file to the Haml layout template

I'm currently working on linking a css file to a haml layout template Within the ApplicationHelper class, I have a method to properly generate html module ApplicationHelper def styletag(sheet_name) "<link rel='stylesheet' href=&a ...

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

Tips for managing credentials and cookies across multiple websites

I have a vision of creating a website similar to Stack Overflow, complete with individual blog pages and applications for each member, all using MVC 3. I want to combine various features from different websites into one cohesive platform. How can I achie ...

Dealing with CSS Overflow Issues: Fixing the Scroll Bug

My current project involves creating a page with fixed links at the top and submit buttons at the bottom. The content in the middle is scrollable using overflow:auto. I've noticed that when I resize the browser window, the scrollbar slowly disappears ...

executing tasks on a sql database with php

Currently, I am delving into the realm of SQL and have devised a table named products. This table consists of columns such as item, price, base, and wholesale. My goal is to enable users to input a number (let's say 15) which signifies their desire t ...

Bootstrap Button Problem: Difficulty arranging buttons in a neat way, unable to position them next to each other

I'm currently working on a real estate website project and have designed a Photoshop template which is uploaded on Behance. Check it out here. Right now, I'm creating the static version of the real estate store template and facing an issue with ...

Easily ajaxify your website without the need for hash or hashbang URLs

Currently enrolled in a web design course, I am eager to explore the world of ajax and how it can enhance our projects. Unfortunately, our instructor focuses solely on design and HTML, leaving us to figure out the more technical aspects on our own. If I m ...

ajax does not function properly with arrays

i'm currently attempting to load data from a text file into an array using ajax, and this is the code i am utilizing: function loadWords(){ var xhr = new XMLHttpRequest(); xhr.open('GET', "dico/francais.html"); xhr.onreadystatec ...

Check out the intriguing dual arrow designs displayed by the .custom-select class in Bootstrap 4

Having an issue with the .custom-select class in Bootstrap-4. There seems to be two overlapping arrow styles: https://i.sstatic.net/Alvpc.jpg .custom-select { position: center; box-sizing: border-box; height: auto; padding: 10px; font-size: ...

Tips for consuming a REST API to retrieve JSON data and assign it to a variable for use in React JS

I'm currently working on developing a shopping application using React.js. I found inspiration from a sample application on https://codepen.io/paulkim/pen/oZLavq , and now I am looking to fetch product information from an API call. I have attempted to ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

Reversing the sequence of code in JavaScript - react native

I'm currently working on tracking the number of times a button is pressed within one second. For the most part, it's functioning correctly as it tracks and displays the count. The issue arises when it displays the button press count from the pr ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

Creating React components with scoped CSS imports

I am facing an issue with my component's CSS structure and import method. About/style.css .AboutContainer { # Some style } p > code { # Some style } When importing the CSS in the component: About/index.js import './style.css&apos ...

Rejuvenating a template generated on the server in AngularJS

I have a specific partial which is a report - simply a static list of names and dates designed for viewing and printing purposes. For efficiency reasons, the report is rendered server-side, so when a report request is made, my API responds with HTML rathe ...

The parsing of Jquery ajax xml is not working as expected

Upon parsing my XML using the code below, everything was working fine until I added a review node. $(document).ready(function generatexml(){ $.ajax({ type: "GET", url: "data/concerts.xml", dataType: "xml", ...

Failure to receive a response from ExpressJS jQuery ajax Post request

I am facing an issue with my Ajax post request as I am unable to retrieve any values in the console. Can anyone point out what might be missing here? Node.js app.post('/register',function(req,res) { //console.log(JSON.stringify(req.body)); ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...