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.
http://opensource.org/licenses/MIT

 


9 Comments

Post a comment
  1. webtady
    Posted on September 29, 2016 at 00:22 Permalink

    thanks for sharing. Amazing plugin.

    Reply
  2. 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
  3. ramazan
    Posted on August 20, 2016 at 22:51 Permalink

    tkanks for sharing, it is required my site

    Reply
  4. 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
  5. Kumsal
    Posted on June 24, 2015 at 20:23 Permalink

    Thanks for sharing.

    Reply
  6. 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