+ Start a Discussion

Javascript in Visualforce

I have some java script that works fine in a standard HTML page.  


The script goes through a calculation to randomly select a number.  This number matches the elements of an array, with each element holding a URL to an image.  The script then displays the image on the screen.  


The idea is on every page refresh a different image is displayed.


How would I add this to visualforce?  I've tried adding the script to a visualforce page but it doesnt work.  I've looked at the developer notes which suggests I need to add the .JS file as a static resource and then reference it from the visualforce page.


Can anyone provide some guidance on how I would use this to have my visualforce page reference the javascript and return a link to a static resource (my javascript array elements all contain static resource paths).


You can add JavaScript directly on to a visualforce page - they render as HTML so there's no problem with that.  What error are you seeing?

Mudasir WaniMudasir Wani

Hi Alanistic,


If you are asking about how to include the resource file in your page,

Then you can use following code.


For  stand-alone file, use $Resource.<resource_name>


<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>

Where MyJavascriptFile is the name of your stand-alone static resource.


To reference a file in an archive, use the URLFOR function.


<apex:includeScript value="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>

Where LibraryJS is your archive static resource heaving the folder 'structure '/base/subdir/file.js'   


For more information visit.





For adding  stand-alone file use the following syntax,

<apex:includeScript value="{!$Resource.Angular}"/>


Where Angular is the Static Resource name, which contain a single file.



For adding multiple files use the following syntax,


 <apex:includeScript value="{!URLFOR($Resource.Angular, 'js/activitycontrollers.js')}"/>


Where Angular is the Static Resource name, js is the Folder name inside the Zip file that you have uploaded, activitycontrollers.js is the File Name.



When you are added images in the Script file, Add those images in Documents folder and Paste that particular image url as follow,


<img src="https://c.na15.content.force.com/servlet/servlet.ImageServer?id=015i0000000XCIz&oid=00Ci0000000Rs1P&lastMod=1373373808000" />


Hope it will helpful for you..




bob_buzzard wrote:

You can add JavaScript directly on to a visualforce page - they render as HTML so there's no problem with that.  What error are you seeing?

I've tried adding the javascript directly to the page.  I don't get an error but the javascript doesn't do anything.  Would there be anything that stops the javascript from executing?  Anything that goes within the script tags doesn't appear at all.