[SalesForce] Using jQuery with apex:tabPanel in visualforce

I am using jQuery library in my visual force page, but I've faced a major problem when I tried to use tabs "apex:tabPanel".

<script src="{!$Resource.jQuery}"></script> <!-- If I delete this script the tabs work !! -->

<apex:tabPanel tabClass="activeTab" inactiveTabClass="inactiveTab">
  <apex:tab label="Tab#1" id="tab1"></apex:tab>
  <apex:tab label="Tab#2" id="tab2"></apex:tab>
</apex:tabPanel>

I get a "JS" errors in the console when I try to click on any tab, but if I delete jQuery library it works. So I guess there is a conflict between jQuery and apex:tabPanel functionality.


Here's what I got in the console

Uncaught ReferenceError: initViewstateTab is not defined 
Uncaught TypeError: Object [object Object] has no method 'dispatchEvent' 
Uncaught ReferenceError: initViewstateTab is not defined 
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
Uncaught TypeError: Object [object Object] has no method 'hasClassName' 
Uncaught TypeError: Cannot call method 'replace' of undefined

Best Answer

The error happens here because of the conflict between jQuery and PrototypeScript libraries. To fix it just use jQuery's noConflict() function:

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

  1. Load the jQuery library first (at the top of the page)
  2. Use apex:includeScript instead of script tag
  3. Then use noConflict() function
  4. Read this great topic Using jQuery in a Visualforce Page from the developer force site

Yout page must look like this then:

<apex:page>
<apex:includeScript value="{!URLFOR($Resource.Scripts,'script/jquery-1.8.1.min.js')}" />

<script>
    jQuery.noConflict();

    // all other javascript stuff...
</script>

<apex:tabPanel switchType="client" tabClass="activeTab" inactiveTabClass="inactiveTab">
  <apex:tab label="Tab#1" id="tab1"></apex:tab>
  <apex:tab label="Tab#2" id="tab2"></apex:tab>
</apex:tabPanel>
Related Topic