Is there any event triggered when the src attribute of an image is modified?

I am currently working on a project where I am dealing with images of different sizes, and my goal is to adjust the parent div size based on the height of the new image.

Within my code, I have set inner, viewOne, and viewTwo as global variables. Here is a snippet of my code:

  viewOne.src = 'path/to/newImage.png';
  viewTwo.src = 'path/to/otherImage.png';

  inner = document.getElementById('innerWindow'); // Parent Div
  viewOne = document.getElementById('viewImgOne'); // Image Object
  viewTwo = document.getElementById('viewImgTwo'); // Image Object

  if(viewOne.clientHeight >= viewTwo.clientHeight) {
    inner.style.height = viewOne.clientHeight + "px";
  } else {
    inner.style.height = viewTwo.clientHeight + "px";
  };

However, there seems to be an issue with the parent div not always resizing correctly after changing the image paths, resulting in extra pixels at the bottom of the div that are not needed.

In addition, I have implemented a window.onresize function to handle resizing the div when the browser window changes, which is functioning properly.

My question is: Is there a way to monitor the src attribute and trigger the resize function only after the images have fully loaded?

Answer №1

To effectively tackle this issue, one strategy is to attach the .load event to all images so you can monitor when an image has completed loading after a src change. It's uncertain if there exists a more straightforward method to detect src changes directly. However, in order for this approach to work seamlessly, it's crucial to bind .load before any modifications are made to the image element's .src attribute.

If you're programmatically generating the image elements, this shouldn't pose a problem. Similarly, if you're recycling the same image tags multiple times, this should not be an impediment (with the exception of the initial load on page load, but that likely isn't a major concern).

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

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

Difficulty accessing PHP information in an external file when using getJSON

In my wos.php file, I have created an array that is then encoded using json_encode and echoed to be used in another file named data.php through jQuery. However, the data is not being received as expected. Here is an example of the array ($recordArray) cre ...

A comparison between XPath and JQuery locators when using Selenium

After discovering that individuals utilize JQuery element-locators in Selenium, I am intrigued by the concept. I would like to inquire about the advantages of using JQuery selectors over XPath selectors. Are they considered more adaptable or quick, parti ...

The Ajax autocomplete feature was unable to find a matching HTTP resource for the requested URI

Seeking assistance with implementing autocomplete functionality on a textbox using data from a web method. The webmethod's browser operation is as follows: http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e The resu ...

Customize Material UI components by incorporating SASS classes

Currently, I am using Material UI components but I want to streamline my styles by moving them all into a .scss file. Right now, I have a significant styles object within the same JavaScript file where I am utilizing the Material UI components. This styles ...

Best practices for structuring directories using Node, Express, and Mongoose

I came across a library structure for an express app, but when using mongoose the model library is utilized differently. Where should I place my schemas? project/ controllers/ posts.js index.js users.js utilities/ dates.js middlewa ...

Is it possible to utilize a Next.js image for triggering a form submission via onClick for Google OAuth?

Disclaimer: Novice User I have successfully created a custom signin page with email and social media authentication using Next.js. Now I would like to customize the styling by incorporating Next.js/Image to replace the submit button with a clickable icon ...

Invoke the function within $mdDialog from the main controller

I have a requirement to execute a method within $mdDialog. This method is passed from the parent component to my directive. <get-data action="getData()" ></get-data> To access the method in my get-data directive. function customDirective() { ...

Creating a CSS style to increase the height of a column within a fixed size overflow container

Is there a way to increase the height of a column within a fixed size overflowed div? When using overflow: auto, setting height: 100% does not extend all the way to the end of the scroll. In my JSFiddle demonstration, I am aiming for the red column to ma ...

Issue with displaying the Bootstrap Autocomplete Input Dropdown

I've been struggling with this issue for hours now. Using Bootstrap 3, I am attempting to implement the bootstrap autocomplete input with ajax. The data is being retrieved successfully through Ajax, and I can confirm that. However, the dropdown menu i ...

Attempting to invoke a static function from a imported ES6 module

Currently, I am utilizing Firefox 56 with the setting dom.moduleScripts.enabled enabled. This configuration allows me to engage with native ES6 modules seamlessly. In my Vue2 component, there is a method that I have defined: import StorageZonesAjaxMethod ...

Space in the middle of a body and a div

After extensively searching for a solution to the issue plaguing my website, I found that there was always an annoying gap at the top of the page. Despite trying various solutions, none seemed to work. Upon inspecting the website in Firefox, I discovered t ...

Troubleshooting jqGrid Error with jsonReader when JSON does not contain 'rows' information

When using jqGrid with Fusion Tables, everything works smoothly if the JSON returns results. However, a problem arises when there are no results because obj.rows is non-existent. This leads to the page breaking while attempting to check the length. Is ther ...

Convert the indices of strings to ObjectIDs in a massive MongoDB database instance

I have a large production database dump with `_id` fields as strings. The length of these strings varies in different collections, and there are numerous relations within the data. I am looking for a solution to change these string `_ids` to `ObjectId` for ...

"Encountering a strange behavior in Vue.js: the created() hook

I made a custom feature to refresh my data from the database by clicking a button: <template> <base-projects :projects="projects" /> </template> <script> import { mapGetters } from 'vuex'; import Projects from './ ...

Guide on converting a buffer to a PDF file using front-end technologies

I utilized Puppeteer to create a buffer containing pdf data and then transmitted it to the frontend application. Below is the code snippet for the backend API: exports.getPDF = async (req, res) => { const { content } = req.query; const browser = ...

Getting the URL of a CSS background image in NodeJS and Express: A step-by-step guide

I've recently learned that using getComputedStyle in a Node environment is not possible due to it being a browser-specific behavior. Despite this, I am still interested in retrieving all background image URLs within Node and downloading them as shown ...

Dealing with errors when using promises in Node.js streams

I stumbled upon this code snippet and I'm trying to figure it out: let generateData = function(length, count, stream, headers) { length--; count++; if (length === 0) { stream.write(headers.map(function(value) {return value + &ap ...

Is there a way to reverse the selection of a row in a kendoui grid?

How can I invert a current selection in a KendoUI grid that is set to "multiple" selection mode? ...

I'm having a strange issue where my code runs perfectly on JSFiddle, but it refuses to work on localhost

I am facing an issue with running my code on my LAMP server localhost, even though it works fine on JSFiddle. Typically, when this happens, it's usually a small mistake that I overlook. However, having multiple sets of eyes look at the problem is alwa ...