1

I want to call some JS function when particular div with class is loaded in my Rails 4 app.

<div class="myClass">
  hello world
</div

How to call some js code only when this div is loaded.

yerassyl
  • 2,958
  • 6
  • 42
  • 68
  • use jquery to check if div with that class exist using lenght() and then call a method.. – Milind Apr 21 '15 at 11:57
  • Define loaded: injected into the page using ajax, or run a particular piece of js when it is present on the page? If using ajax: how do you inject the html? – nathanvda Apr 21 '15 at 14:04

3 Answers3

0

I dont think, it is relevant to rails

There can be two approach:

1: write a JS code below your html DIV

<div class="myClass">
  hello world
</div
<script type="text/javascript">
yourfuncion();
</script>

2: call a function when document is ready, like:

$(document).ready(function(){
    yourfuncion();
});
user3118220
  • 1,438
  • 12
  • 16
0

You can bind to DOMNodeInserted to check when a certain element has been loaded.

Example:

$(document).on('DOMNodeInserted', function(event){
  if($(event).hasClass("myClass")){
    // do something
  }
});

Use with caution if your page is large as this is known to cause performance concerns. Alternative to DOMNodeInserted

Community
  • 1
  • 1
fylooi
  • 3,840
  • 14
  • 24
-1

What you can do is check is the div is loaded every few seconds until it's loaded.

$(document).ready(function(){
    checkDiv();
});

function checkDiv () {
  if($('#myDiv').is(':visible'))){ 
    // what you whant
  } else {
    setTimeout(checkDiv, 50); //wait and try again. 
  }
}

I hope it's helps.

gon250
  • 3,405
  • 6
  • 44
  • 75
  • Given you've put it in a `document.ready();` surely it will always have been loaded in the first time that runs? – j-dexx Apr 21 '15 at 09:39
  • Was my mistake. if the div is not visible it's going to wait 50ms and then execute again until it's loaded. @japed – gon250 Apr 21 '15 at 10:03