Hello! Again faced a strange problem, now associated with JavaScript . There is a page, on it simple JavaScript , jQuery also connected.

 function initTooltips() { $(window).load(function() { $('.tt-trigger').each(function() { var index = $(this).data('tooltip'); var pPos = $(this).position(); var pWidth = $(this).outerWidth(); var pHeight = $(this).outerHeight(); $('.tooltip.tt[data-tooltip="' + index + '"]').css({ width: pWidth + 'px', top: (pPos.top + pHeight) + 'px', left: (pPos.left) + 'px' // pPos.left = 0, 150, 300 .. }); }); }); $(window).resize(function() { $('.tt-trigger').each(function() { var index = $(this).data('tooltip'); var pPos = $(this).position(); var pWidth = $(this).outerWidth(); var pHeight = $(this).outerHeight(); $('.tooltip.tt[data-tooltip="' + index + '"]').css({ width: pWidth + 'px', top: (pPos.top + pHeight) + 'px', left: (pPos.left) + 'px' }); }); }); }; $(function() { initTooltips(); }); 

So, the code stops working ( $(this).position().left starts issuing 0 for all iterations) in three situations: if I take the code from load and resize into a separate function, if I take the code outside $(window).load() ( document not so ready , apparently) or if I switch from this page to some other one, and then return to the back button of the browser (it starts working after refreshing the page). For example, this code no longer works (but it does not generate errors in the console, just all the necessary variables are zero):

 function foo() { $('.tt-trigger').each(function() { var index = $(this).data('tooltip'); var pPos = $(this).position(); var pWidth = $(this).outerWidth(); var pHeight = $(this).outerHeight(); $('.tooltip.tt[data-tooltip="' + index + '"]').css({ width: pWidth + 'px', top: (pPos.top + pHeight) + 'px', left: (pPos.left) + 'px' // pPos.left = 0, 0, 0 .. }); }); }; function initTooltips() { $(window).load( foo() ); $(window).resize( foo() ); }; $(function() { initTooltips(); }); 

That is, the behavior is very strange, but I see no reason for this. Thanks in advance for your help.

  • Have you shown code that works? Very good. Now please show the code that does not work. - Igor
  • The problem with the "Back" button is due to the fact that the JavaScript code executes before compiling less (via less.js). Accordingly, when pre-prepared CSS is connected, the problem disappears, so it will not be in production. However, I still don’t understand why Chrome interprets JavaScript so strangely when I press the back button. - Urffly

1 answer 1

Well, that's another matter.

You have correctly put the same repeatable code in a separate function. But now you need not to call your handler, but pass a link to it:

 function initTooltips() { $(window).load( foo ); $(window).resize( foo ); };