Magento – jQuery conflict in the product view page

javascriptjquerymagento-1.7

I implement jquery lazyloads to load product images on scrolling..

I added the following codes to view.phtml

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/jquery.lazyload.js?v=1.9.7'); ?>"></script>
<script type="text/javascript" charset="utf-8">

$(function() {
 $("img.lazy").lazyload({
     effect : "fadeIn"
 });
});

</script>

<?php foreach ($galleryCollection as $_image): ?>
        <img class="lazy products" data-original="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile())->keepFrame(false)->resize(426,700); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'image'), null, true);?>" />                                       
<?php endforeach; ?>

The out put is fine as i expected.Images are loading on scroll.
BUT
Unable to click the magento view option button.
Code for view option button click is below.

<script type="text/javascript">

    Event.observe($('show_bundle_options'),"click",function(){
    $('bundle_options').show();
    $('bundle_options_background').show();
    }); 
</script>

I can understand that this is jQuery conflict.I tried several ways to add jQuery.noConflict(); its not working.
If the options works fine images are not loading if the images load Options are not working.

Is there any other ways to load the image on scrolling the page?

I am using magento 1.7 version.

Please help me to sort it out.

Best Answer

Magento uses Prototype JS which has already claimed the $ variable. You need to use jQuery in "no conflict" mode so jQuery won't also claim the $ variable:

<script>
jQuery.noConflict();
</script>

After this, you cannot use $() to use jQuery, because then you call Prototype. You have to use the full name: jQuery(). You can change your self written scripts by:

  1. Replacing all uses of $ by jQuery
  2. Wrap your scripts in an anonymous function passing jQuery as a parameter:

    (function($) {
         // You can simply use $ here
         $('selector').dosomething();
    })(jQuery);
    

The jquery.lazyload.js library is well written and is able to operate in both normal mode and conflict mode. There's no need to change the files of this library (replacing all uses of $ by jQuery) as it is already making use of the anonymous function method, see jquery.lazyload.js:

16.  (function($, window, document, undefined) {
17.      var $window = $(window);
18.  
19.      $.fn.lazyload = function(options) {

             // *SNIP* (lots of code...)

240.     });
241. 
242. })(jQuery, window, document);