Use jQuery to monitor DOM element size changes
Cause
When I was writing a page today, I suddenly had such a need. Since the height of the parent element (a DIV) is a fixed value calculated by javascript, a multi-talk plug-in was added to it. After the user comments, the height attribute of the child element (DIV) is increased, causing the child element to overflow. But I didn’t know how to add a callback function for Duosuo’s comment button, so I thought of recalculating the height of the parent element based on the size change of the child element.
onresize?
Usually, a callback function that modifies the layout is triggered when the entire browser window changes. The resize event of the window object is used, and is bound using:
window.onresize = callback;
. But according to the target of the resize event is defaultView (window), please see MDN's resize document for details. That is to say, only the window object has a resize event, so I thought of using jquery's own event mechanism to simulate a resize event on an ordinary element
Implementation idea of using jQuery events
You can think of a relatively simple way:
1. When the element is bound to the resize object, record the width and height of the element
2. Use requestAnimationFrame, setTimeout, and setInterval to query its width and height at regular intervals. If it is different from the recorded width and height, run the callback function and update the recorded width to height
jQuery plug-in
Ben Alman wrote a jQuery plug-in for this function. This is the portal.
The code (core part) of the plug-in. For detailed code, please check the content of Ben Alman’s blog:
(function($, window, undefined) { var elems = $([]), jq_resize = $.resize = $.extend($.resize, {}), timeout_id, str_setTimeout = 'setTimeout', str_resize = 'resize', str_data = str_resize + '-special-event', str_delay = 'delay', str_throttle = 'throttleWindow'; jq_resize[str_delay] = 250; jq_resize[str_throttle] = true; $.event.special[str_resize] = { setup: function() { if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); elems = elems.add(elem); $.data(this, str_data, { w: elem.width(), h: elem.height() }); if (elems.length === 1) { loopy(); } }, teardown: function() { if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var elem = $(this); elems = elems.not(elem); elem.removeData(str_data); if (!elems.length) { clearTimeout(timeout_id); } }, add: function(handleObj) { if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; } var old_handler; function new_handler(e, w, h) { var elem = $(this), data = $.data(this, str_data); data.w = w !== undefined ? w : elem.width(); data.h = h !== undefined ? h : elem.height(); old_handler.apply(this, arguments); } if ($.isFunction(handleObj)) { old_handler = handleObj; return new_handler; } else { old_handler = handleObj.handler; handleObj.handler = new_handler; } } }; function loopy() { timeout_id = window[str_setTimeout](function() { elems.each(function() { var elem = $(this), width = elem.width(), height = elem.height(), data = $.data(this, str_data); if (width !== data.w || height !== data.h) { elem.trigger(str_resize, [data.w = width, data.h = height]); } }); loopy(); }, jq_resize[str_delay]); } })(jQuery, this);
jQuery is The developer of the jQuery plug-in provides an interface for adding custom events. For details, please refer to the jQuery official documentation. Here is the typical way to add jQuery custom events, which has three hooks:
1. setup: The setup hook is called the first time an event of a particular type is attached to an element. Executed when first binding. If false is returned, the default method is used to bind the event
2. teardown: The teardown hook is called when the final event of a particular type is removed from an element. If this method is specified, it will be executed before removing the event handler program (removeEventListener). If false is returned, the default binding event will be removed
3. add: Each time an event handler is added to an element through an API such as .on(), jQuery calls this hook. Every time an event is bound to an element, this method
setup, teardown and add three hooks will be executed. The first thing a hook does is to detect whether the object is a window object, and then handle it specially according to the window object, because the window object itself has a resize event
As you can see from the setup hook, when initializing the entire event processing , create an element queue. Every element in the queue puts the width and height in the data, and then starts the loopy function every 250ms. In the loopy function, it is judged whether there is a change. If there is a change, the callback function is triggered and the data is updated. width and height
As you can see from the teardown hook, when the element removes the event, you only need to remove the element from the element queue and clear the data in the element. If it is the last element in the element queue, loopy will no longer continue to be executed.
In the add hook, the callback function is wrapped
You can see a simple jQuery Implementation mechanism of custom function
The above is the detailed content of Use jQuery to monitor DOM element size changes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy
![How to increase disk size in VirtualBox [Guide]](https://img.php.cn/upload/article/000/887/227/171064142025068.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
We often encounter situations where the predefined disk size has no room for more data? If you need more virtual machine hard disk space at a later stage, you must expand the virtual hard disk and partitions. In this post, we will see how to increase disk size in VirtualBox. Increasing the disk size in VirtualBox It is important to note that you may want to back up your virtual hard disk files before performing these operations, as there is always the possibility of something going wrong. It is always a good practice to have backups. However, the process usually works fine, just make sure to shut down your machine before continuing. There are two ways to increase disk size in VirtualBox. Expand VirtualBox disk size using GUI using CL
