This website uses cookies to personalise ads and to analyse traffic ok
web design

Event based jQuery element resize

The script does not use any kind of timer(s) to detect size changes. It uses the resize event on (invincible) iframe(s) which makes it perform much better than other solutions which use timers to poll element size. The script detects size changes made from JS, CSS, animations etc. and it works on any element able to contain other elements (e.g. div, p, li etc.).

Current version 1.0.1

jQuery plugin

How to use it

Download plugin archive and extract/upload mresize.min.js to your web server.

Include jQuery library (if your project doesn’t use it already) and mresize.min.js in the head tag or at the very bottom of your document, just before the closing body tag

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/path/to/mresize.min.js"></script>

Call jQuery mresize function on your element(s)

<div class="resizable"> ... </div>
<script>
    (function($){
        $(window).load(function(){
            $(".resizable").on("mresize",function(){
                console.log($(this));
            });
        });
    })(jQuery);
</script>

The plugin script has a default resize throttle of 100 milliseconds. To change its value you can modify the throttle property of "mresize" data object:

$(selector).data("mresize").throttle=100;

For example, to add the resize event and disable throttling you can do:

<script>
    (function($){
        $(window).load(function(){
            $(".resizable").on("mresize",function(){
                console.log($(this));
            }).each(function(){
                $(this).data("mresize").throttle=0;
            });
        });
    })(jQuery);
</script>

Video tutorial (from webucator.com)

Check more jQuery courses at webucator.com

Pure javascript tutorial

Append the resize event markup in your element

<div id="test">
  <!-- some content... -->
  <p>...</p>
  <!-- resize markup -->
  <div class="resize">
    <iframe></iframe><iframe></iframe>
  </div>
</div>

Add the resize event CSS

/* test element */
#test{
  position: relative;
  width: 60%;
  background: #ccc;
  resize: both;
  overflow: auto;
}
/* resize */
.resize{
  position :absolute;
  width :auto;
  height :auto;
  top :0;
  right :0;
  bottom :0;
  left :0;
  margin :0;
  padding :0;
  overflow :hidden;
  visibility :hidden;
  z-index :-1;
}
.resize iframe{
  width: 0;
  height: 100%;
  border: 0;
  visibility: visible;
  margin: 0;
}
.resize iframe:first-child{
  width: 100%;
  height: 0;
}

Include the resize script at the bottom of the document

<script>
  var t=document.getElementById("test"), p=t.children[0];
  Array.prototype.forEach.call(document.querySelectorAll(".resize iframe"),function(el){
    (el.contentWindow || el).onresize=function(){
      //do something...
      p.innerHTML=t.offsetWidth+"x"+t.offsetHeight;
    }
  });
</script>

Simple javascript class

var mresize=function(selector,callback){
    [].forEach.call( document.querySelectorAll(selector), function(el){
      el.mr=[el.offsetWidth,el.offsetHeight];
    el.insertAdjacentHTML("beforeend","<div class='mresize' style='position:absolute;width:auto;height:auto;top:0;right:0;bottom:0;left:0;margin:0;padding:0;overflow:hidden;visibility:hidden;z-index:-1'><iframe style='width:100%;height:0;border:0;visibility:visible;margin:0'></iframe><iframe style='width:0;height:100%;border:0;visibility:visible;margin:0'></iframe></div>");
    [].forEach.call( el.querySelectorAll(".mresize iframe"),function(frame){
      (frame.contentWindow || frame).onresize=function(){
        if(el.mr[0]!==el.offsetWidth || el.mr[1]!==el.offsetHeight){
          if(callback) callback.call(el);
          el.mr[0]=el.offsetWidth; el.mr[1]=el.offsetHeight;
        }
      }
    });
  });
}

Usage

<script>
  var resize=new mresize(selector,function(){
    //do something...
  });
</script>

License

This work is released under the MIT License.
You are free to use, study, improve and modify it wherever and however you like.
https://opensource.org/licenses/MIT

 


32 Comments

Post a comment
  1. [email protected]
    Posted on November 14, 2023 at 15:19 Permalink

    Great article! The concept of event-based jQuery element resize is extremely valuable, especially in the dynamic world of web development. I appreciate the detailed explanation of the techniques and the code snippets provided. Understanding how to efficiently handle element resizing is crucial for creating responsive and user-friendly interfaces. The use of jQuery for this purpose adds an extra layer of flexibility and simplicity. Have you encountered any specific challenges or interesting use cases while implementing this approach? I’d love to hear more about real-world applications or any additional tips you might have. Thanks for sharing your insights!

    Reply
  2. Demon Slayer: Kimetsu No Yaiba 4. Sezon 5. Bölüm
    Posted on May 7, 2023 at 06:16 Permalink

    Thank you for this beautiful article. I found lot’s of usefull content here…

    Reply
  3. naba
    Posted on February 8, 2023 at 08:39 Permalink

    “Great post! I really enjoyed reading it and found it informative.

    React JS Interview Questions and Answers !

    Reply
  4. Manolo
    Posted on January 29, 2023 at 04:57 Permalink

    Great post! Using invincible iframe is great fir performance!

    Reply
  5. canlidiziizlesene
    Posted on January 15, 2023 at 22:43 Permalink

    Yes! Very useful tips presented here. Thank you very much.

    Reply
  6. inno veneers
    Posted on January 11, 2023 at 18:52 Permalink

    this is really helpful thank you for sharing

    Reply
  7. Parkobility
    Posted on December 31, 2022 at 01:22 Permalink

    this is very useful content thank you for sharing

    Reply
  8. aycup
    Posted on April 2, 2022 at 15:38 Permalink

    Hi, Thanks for sharing.

    Reply
  9. codepopular
    Posted on May 2, 2021 at 11:27 Permalink

    This is very effective website. i we have learn many thing from here. also using some assets to our website.
    Specially Thanks <a href="https://codepopular.com">CodePopular.Com</a>

    Reply
  10. Madinah Grill
    Posted on April 22, 2021 at 08:57 Permalink

    I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Thank you for your good work.

    Reply
  11. Anik Biswas
    Posted on March 28, 2021 at 17:58 Permalink

    Thanks for sharing, it is very informative and useful for starter.

    Reply
  12. Positive News
    Posted on October 2, 2020 at 17:51 Permalink

    Wow, great Plugin!

    This is the first time I read the whole article.
    Thank you so much it is helpful and clear

    Reply
  13. istoç kozmetik
    Posted on April 27, 2020 at 00:08 Permalink

    Thank you bro. I use

    Reply
  14. Baytronik
    Posted on March 13, 2020 at 04:36 Permalink

    Thank thanks

    Reply
  15. Baytronik
    Posted on March 1, 2020 at 04:18 Permalink

    Thank you!!

    Reply
  16. batuhan
    Posted on June 23, 2019 at 23:13 Permalink

    thanks for sharing… Very nice

    Reply
  17. [email protected]
    Posted on February 26, 2019 at 12:43 Permalink

    nice post

    Reply
  18. vijayaustin
    Posted on February 11, 2019 at 08:53 Permalink

    Thanks for sharing nice work

    Reply
  19. Lianamelissa
    Posted on December 3, 2018 at 13:24 Permalink

    your information is really awesome as well as it is very excellent and i got more interesting information from your blog.

    Reply
  20. Teknoloji incelemeleri
    Posted on October 24, 2018 at 18:51 Permalink

    Thanks for sharing.

    Reply
  21. katherine
    Posted on June 8, 2018 at 12:37 Permalink

    Thank you for this beautiful article. I found lot’s of usefull content here…can you provide some posts about json.

    Reply
  22. Liana
    Posted on April 26, 2018 at 07:59 Permalink

    Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information’s, can you provide some links of core java for selenium.

    python

    Reply
  23. knnknn
    Posted on February 6, 2017 at 21:36 Permalink

    Doesn’t work with iframes, i.e. nothing gets triggered when an iframe gets resized.

    Reply
  24. webtady
    Posted on September 29, 2016 at 00:22 Permalink

    thanks for sharing. Amazing plugin.

    Reply
  25. Elshan Siradjov
    Posted on August 25, 2016 at 13:27 Permalink

    Hi,

    I have a table Element loaded in a div. The rows in the table ( – elements) change position from time to time.
    What I want to do is basically, the scrollbar should scroll to the new position of the row which is being clicked on /selected by the user.
    I thought autoScrollOnFocus would work but unfortunately I haven’t found a solution yet.

    Thank you in advance!

    Reply
  26. ramazan
    Posted on August 20, 2016 at 22:51 Permalink

    tkanks for sharing, it is required my site

    Reply
  27. JV
    Posted on November 18, 2015 at 20:48 Permalink

    I don’t suppose it’s possible to add the event dynamically on elements that don’t yet exist in the DOM like so

    $(document).on(“click”, “.dont-exist-yet”, function() {

    });

    Reply
    • malihu
      Posted on November 19, 2015 at 22:05 Permalink

      Ah no… but you could probably simulate it like this:

      var live=setInterval(function(){ if($("#elemID").length) clearInterval(live); //stop polling after element is available $("#elemID").on("mresize",function(){ //do your thing... }); },100);

      Hope this helps

      Reply
  28. Kumsal
    Posted on June 24, 2015 at 20:23 Permalink

    Thanks for sharing.

    Reply
  29. JV
    Posted on April 10, 2015 at 23:51 Permalink

    Another amazing plugin. Do you think this could be used for responsive design based on an elements width rather than the window width, which is what CSS media-queries bases it on?
    Also would you consider creating an AJAX plugin?

    Reply
    • malihu
      Posted on April 14, 2015 at 01:11 Permalink

      Hello,

      The plugin triggers the callback function on any kind of resize (CSS queries, JS, window resize etc.), so normally, you’d want to do something like this:

      $(".resizable").on("mresize",function(){ var $this=$(this),c=$this.data("mrclass"),nc,w=$this.width(); if(c) $this.removeClass(c); if(w>=1280){ nc="min-width-1280"; }else if(w>=800){ nc="min-width-800"; }else if(w>=480){ nc="min-width-480"; } $this.addClass(nc).data("mrclass",nc); }).trigger("mresize");

      And then in your CSS:

      .resizable{ /* rules */ } .resizable.min-width-1280{ /* rules */ } .resizable.min-width-800{ /* rules */ } .resizable.min-width-480{ /* rules */ }

      Reply
      • JV
        Posted on April 17, 2015 at 20:50 Permalink

        Sweet. Maybe in a future update the plugin could be capable of detecting position changes as well.

        Reply

Post a comment

Your e-mail is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can write or copy/paste code directly in your comment using the <code> tag:
<code>code here...</code>
You may also use the data-lang attribute to determine the code language like so:
<code data-lang-html>, <code data-lang-css>, <code data-lang-js> and <code data-lang-php>

css.php