+ Start a Discussion
Michael3.BrownMichael3.Brown 

Extremely simple Javascript function no longer working on Visual Force

Hello,

 

I was working on my visual force page with some Javascript. I noticed it wasn't triggering, so I made my code as simple as possible: to generate a popup as soon as the page loads. However, my code will not work. I copied my code into another one of my VisualForce pages, and it works there, but I cannot figure out why it won't work in this specific page.

 

<script language="javascript" type="text/javascript">
function hideEmptyRows()
{        
    alert('test');
}    
</script>
<body onLoad="hideEmptyRows()">

 I'm having trouble understanding why this would work on one VisualForce page, but not another.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Are the page attributes the same in both cases?  I seem to recall that onload handlers work well when you don't pull in the header and sidebar, but not so well when those are present.

 

You could try calling your function in a javascript block at the end of the page - I've used that in the past and seen much the same behaviour as an onload handler.

All Answers

aballardaballard

Sounds like something else in the page is resetting body.onload to something different....

bob_buzzardbob_buzzard

Are the page attributes the same in both cases?  I seem to recall that onload handlers work well when you don't pull in the header and sidebar, but not so well when those are present.

 

You could try calling your function in a javascript block at the end of the page - I've used that in the past and seen much the same behaviour as an onload handler.

This was selected as the best answer
Michael3.BrownMichael3.Brown

Thanks, Bob!  I don't know why, but that was the issue. After disabling my header and sidebar, the Javascript function worked.

 

For future reference, though, in case I need to keep the header and sidebar, how would you set up a javascript block at the end. Does it involve using a special apex tag?

 

Thanks,

Mike

bob_buzzardbob_buzzard

No, nothing special involved.

 

Many browsers (chrome especially) interpret the javascript as it is encountered.  So if you have JS at the top of the page, but it refers to an element later in the page, you can hit problems.   Also, scripts earlier in the page may stop the rest of the page rendering until they have completed.

 

You'd simply finish off your page with script similar to the following:

 

 

<script>

 --- javascript goes here ---

</script>

</apex:page>

 

The onload event fires when the page is rendered, and if you put your script at the bottom of the page the effect will be similar for most modern browsers.  Like most HTML/JavaScript, its not an exact science :)