0

I know this may sound awkward but when I try to call a function without giving a parameter there is no problem everything is ok. However, when I call it with a parameter, I get "Cannot read property 'style'" error.

I have a preloader in my dashboard page to show to users while loading the page. On page load I hide it by using the following code.

this.hidePreLoader = function() {
    document.getElementById('preLoader').style.display = 'none';
};

$(document).on('ready', this.hidePreLoader);
$(document).on('page:load', this.hidePreLoader);

$(document).on('turbolinks:load', this.hidePreLoader);

Above code works perfectly and I get what I want using it. However, when I add a parameter to the code, I get "Cannot read property 'style'" error.

this.hidePreLoader = function(param) {
    document.getElementById('preLoader').style.display = 'none';
};

$(document).on('ready', this.hidePreLoader('ready'));
$(document).on('page:load', this.hidePreLoader('page:load'));
$(document).on('turbolinks:load', this.hidePreLoader(turbolinks:load));

I can't see what I'm missing, is there is problem with that code ?

Note, Actually I write coffeescript, this one is javascript equivalent and problem on '.style.display = 'none';' as I see on browser console. And I use ruby on rails for server side,

Thanks.

Hilmi Yamcı
  • 463
  • 8
  • 20
  • 1
    Possible duplicate of [Difference between assigning event handler to method with and without parentheses](https://stackoverflow.com/questions/20854084/difference-between-assigning-event-handler-to-method-with-and-without-parenthese) and https://stackoverflow.com/questions/15775469/when-to-use-parentheses-with-javascript-function – yuriy636 Nov 18 '17 at 22:35

2 Answers2

0

In first code you pass a function 'hidePreLoader' as a parameter, but in the second one you pass the result of the function 'hidePreLoader' which is undefined.

Try to do something like this:

this.hidePreLoader = function(param) {
    document.getElementById('preLoader').style.display = 'none';
};

$(document).on('ready', function(){ this.hidePreLoader('ready'); });
$(document).on('page:load', function(){ this.hidePreLoader('page:load') ;});
$(document).on('turbolinks:load', function() {this.hidePreLoader(turbolinks:load) ;});
Tazos333
  • 576
  • 4
  • 11
0
    function myFunction(param) {
    document.getElementById('preLoader').style.display = 'none';
};

$(document).on('ready', function(){ myFunction("test") });
$(document).on('page:load', function(){ this.hidePreLoader('page:load') ;});
$(document).on('turbolinks:load', function() {this.hidePreLoader('turbolinks:load') ;});
Orhan Esin
  • 46
  • 7