Question

I have created a tab-menu for my website. Following JavaScript function works well when I run them on localhost -

(function ($) {
    var tab = $(".xmenu > .xmenu-nav > li > a"),
        content = $(".xmenu > .xmenu-content > div");
    tab.click(function (e) {
        content.removeClass("active");
        tab.removeClass("active");
        $(this).addClass("active");
        $($(this).attr("href")).addClass("active");
        e.preventDefault();
    });
})(jQuery)

But when I use them on my site they does not work. The file that contains above anonymous function (xmenu.js) is loaded correctly after jQuery 1.10. You can check it here. When I click on multi-trip it does not work as expected, but when I run above function in console it started working well.

Does someone knows why above function does not run when the file (xmenu.js) is loaded, but works well when I copy and paste it from the file to console and hit enter.

Thank you in advance!

Also check this JSFiddle, its working well here.

Était-ce utile?

La solution

You should load the function on DOM ready. This can be done via jQuery's .ready(), or its shorthand syntax, which I applied to the provided code:

    jQuery(function($) {
        var tab = $(".xmenu > .xmenu-nav > li > a"),
            content = $(".xmenu > .xmenu-content > div");
        tab.click(function (e) {
            content.removeClass("active");
            tab.removeClass("active");
            $(this).addClass("active");
            $($(this).attr("href")).addClass("active");
            e.preventDefault();
        });
    });

This should load the tab switching script after your page has "initialised": after the DOM is ready to be used, which is exactly what you're using when you do something like $(".xmenu > .xmenu-nav > li > a").

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top