Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I be sharing Javascript functions across multiple pages?

I don't completely understand how javascript works in an OOP model, so I come to stack overflow for wisdom.

My example code:

(function($) {
var $container = $('#container');
var $sidebar = $('#sidebar');


// Sidebar  
var currTab = $('#s1');

if(currTab) {
    currTab.parent().parent().parent().addClass('selectedTop');
    currTab.find(".sideContent").delay(300).slideToggle("slow");
    currTab.addClass('selected');
}

$('#sideTop').delegate('li', 'hover', function(event) {
    var $this = $(this);
    if (event.type == 'mouseenter') {
        if(!$this.hasClass("selected")){
            $this.siblings(".selected").children(".sideContent").toggle();
            $this.siblings(".selected").removeClass('selected');
            $this.find(".sideContent").toggle().addClass('selected');
            $this.addClass('selected');
        }
    }
});


})(this.jQuery);

This code caches my container and sidebar div and controls the hovering of tabs on my sidebar. These will be on every page, so I originally just included the js file on each page and it works as usual. Now I've gotten to a point where I want to customize each page with a specific tab of the sidebar open by default (defined by the currTab variable). When set, it will open by default, and stay open after the mouse leaves the sidebar.

I haven't found a way to customize currTab on each page without having to completely re-paste all the code associated with the sidebar, making any updates to the script cumbersome.

How should I be approaching this? Thanks

like image 928
Steve Kelly Avatar asked Aug 14 '26 12:08

Steve Kelly


1 Answers

I'm sorry to have caused confusion with my lack of understanding, but one of the related questions answered mine in a way I didn't know how to search for:

He setup a "class" first, which could be included as a seperate JS, then communicated using jQuery.ClassName(options)

I've tried it and it works perfectly, seperating the code that is consistent, with the values that will change on each page.

(function($){
var undefined;

$.ClassName = function(options){
    var self = this;
    var cfg = $.extend(true, {}, this.defaults, options);

    // ********************
    // start:private
    // ********************
    function _init(){

    };

    // ********************
    // start:public
    // ********************
    this.methodName = function(){

    };

    _init();
};

$.ClassName.prototype.defaults = {};
})(jQuery);
like image 92
Steve Kelly Avatar answered Aug 17 '26 02:08

Steve Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!