Dio Cane
Dio Cane

Reputation: 83

Converting jQuery to no conflict mode

Here's a script I'm using.

$(window).load(function() {
$('#edifici, #artistici, #industriale, #fotovoltaico, #veterinaria, #architettonici').hide();

if (!!window.location.hash) {
    var hash = window.location.hash;
    var $content = $(hash);
    showContent($content)
}

$('.home').click(function () {
    var id = this.id.replace('mostra_', '');
    var $content = $('#' + id + ':not(:visible)');
    if ($('.current').length === 0) {
        showContent($content)
    } else {
        $('.current').fadeOut(600, function () {
            showContent($content)
        });
    }
});

function showContent(content) {
    content.fadeIn(600);
    $('.current').removeClass('current');
    content.addClass('current');
}
});

As per this guide, to use it in WordPress (which has jQuery in no-conflict mode) I modified my script to

jQuery.noConflict();

jQuery(window).load(function($) {
$('#edifici, #artistici, #industriale, #fotovoltaico, #veterinaria, #architettonici').hide();

if (!!window.location.hash) {
    var hash = window.location.hash;
    var $content = $(hash);
    showContent($content)
}

$('.home').click(function () {
    var id = this.id.replace('mostra_', '');
    var $content = $('#' + id + ':not(:visible)');
    if ($('.current').length === 0) {
        showContent($content)
    } else {
        $('.current').fadeOut(600, function () {
            showContent($content)
        });
    }
});

function showContent(content) {
    content.fadeIn(600);
    $('.current').removeClass('current');
    content.addClass('current');
}
});

Unfortunately it doesn't seem to work properly... what am I doing wrong?

Upvotes: 2

Views: 684

Answers (1)

Emil A.
Emil A.

Reputation: 3445

jQuery.noConflict();

Description: Relinquish jQuery's control of the $ variable.

This means jQuery will not use $ anymore, so it will clear all conflicts with other libraries.

To use $ internally you can do the following:

You can wrap the existing code into an anonymous function and pass jQuery as an argument, for example:

(function ($) {

    // use $ here
    $('#hello').html('world');

})(jQuery);

or use a shortcut offered by jQuery:

jQuery(function($) {

    // use $
    $('#hello').html('world');

});

ready method also passes the jQuery object:

jQuery(document).ready(function ($) {
    // ...
});

Upvotes: 6

Related Questions