Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Configuring JQuery Not to Conflict with Other Libraries

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 206
    Comment on it

    Configuring JQuery Not to Conflict with Other Libraries

    If jQuery is loaded on the same page as another JavaScript library, both libraries may have implemented the $ variable, which results in only one of those methods working correctly.

    Solution :

    Lets say you inherit a web page that you need to update, and the previous programmer used another JavaScript library like Prototype, but you still want to use jQuery. This will cause a conflict, and one of the two libraries will not work based on which library is listed last in the page head. If we just declare both jQuery and Prototype on the same page like so:

    <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
    <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    

    this will cause a JavaScript error: element.dispatchEvent is not a function in prototype.js. Thankfully, jQuery provides a workaround with the jQuery.noConflict() method:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>Chapter 3 - Recipe 7 - Configuring jQuery to free up a conflict with
    another library</title>
    <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
    <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
    <!--
    jQuery.noConflict();
    // Use jQuery via jQuery(...)
    jQuery(document).ready(function(){
    jQuery("div#jQuery").css("font-weight","bold");
    });
    // Use Prototype with $(...), etc.
    document.observe("dom:loaded", function() {
    $('prototype').setStyle({
    fontSize: '10px'
    });
    });
    //-->
    </script>
    </head>
    <body>
    <div id="jQuery">Hello, I am a jQuery div</div>
    <div id="prototype">Hello, I am a Prototype div</div>
    </body>
    </html>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: