0

I am attempting to use the on() method inside of a function in order to replace the ready() method so I can use more than one event to trigger a function. Here is the general function I am wanting to use it in:

function tableImgScale() {
$(function () {
    var bandTableHeight = $('#banddetails').height() + "px";

    $(document).ready(function () {
        $('#banddetails td:nth-child(1)').css({"height": bandTableHeight, "overflow": "hidden"});
        $('#banddetails td img').css({"display": "block", "width": "100%", "height": "100%", "objectFit": "cover"});
    });
});
}

So, in simpler terms, I am trying to replace: $(document).ready(function () {...
with: $(document).on('ready resize', function () {...

But it will not work. However, the function with the instance of the .ready() method works perfectly fine. Any help would be appreciated.

Lefty.dev
  • 120
  • 1
  • 11
  • This link could help you http://stackoverflow.com/questions/40442779/events-load-and-ready-not-firing/40443935#40443935 – Geeky Dec 10 '16 at 06:56
  • @Geeky Hmm, would surely be a shame if we can't do this the way I wanted, but I guess the workaround is still...well, a workaround. – Lefty.dev Dec 10 '16 at 07:06

1 Answers1

0

You don't need the call to $(document).ready at all.

Inside your tableImgScale function, you write:

$(function () {
   // stuff
});

...which is another way of waiting for the document to be ready before calling a function. Thus, your inner call to $(document).ready is unnecessary. However, if you want your CSS adjustments to happen when the document is ready as well as on resize, I would extract that logic into its own function so that you can call it immediately, as well as setting it as a listener for resize.

function tableImgScale() {
  $(function() {
    function adjustBandDetails() {
      $('#banddetails td:nth-child(1)').css({
        "height": bandTableHeight,
        "overflow": "hidden"
      });
      $('#banddetails td img').css({
        "display": "block",
        "width": "100%",
        "height": "100%",
        "objectFit": "cover"
      });
    }
    var bandTableHeight = $('#banddetails').height() + "px"
    adjustBandDetails()
    $(document).on('resize', adjustBandDetails)
  });
}
gyre
  • 16,369
  • 3
  • 37
  • 47
  • This does the resize event like I wanted it to, however, the css commands inside that third nested function do not load at first like when I have it as `$(document).ready(...` – Lefty.dev Dec 10 '16 at 07:04
  • Just updated my answer to add that functionality :) – gyre Dec 10 '16 at 07:06
  • Like in Geeky's comment, I might just have to make another function for the resize event. – Lefty.dev Dec 10 '16 at 07:07