6
\$\begingroup\$

I have made a gallery function, this function handles three different types of gallery, one with horizontal nav, other vertical and last one vertical with no nav.

function vid() {
    var vid = $(".videoBg"),
        btn = $(".wVid"),
        wrap = $(".home");
    $(wrap).css({
        "margin-top": "220px"
    });
    $(vid).addClass('active');
    $(btn).on("click", function() {
        var vidH = $(vid).height();
        if ($(vid).hasClass('active')) {
            $(wrap).css({
                "margin-top": vidH - 25 + "px"
            });
            $(this).css({
                "top": vidH - 100 + "px",
                "background-position": "top center"
            });
            $(this).text("Close");
            $(vid).removeClass('active');
        } else {
            $(wrap).css({
                "margin-top": "220px"
            });
            $(this).css({
                "top": "100px",
                "background-position": "bottom center"
            });
            $(this).text("Watch Video");
            $(vid).addClass('active');
        }
        return false;
    });
}

function showHide() {
    var btn = $(".postComment button");
    var popUp = $(".postComment .comForm.pForm");
    var popUpT = $(".postComment .comForm.thanks");
    var close = $(".postComment .comForm .cls");
    var submt = $(".postComment .comForm button");
    $(popUp).hide();
    $(popUpT).hide();
    $(btn).on("click", function() {
        $(popUp).show();
        $(close).on("click", function() {
            $(this).parent().hide();
            return false;
        });
        $(submt).on("click", function() {
            $(popUpT).show();
        });
    });
}

function gallery(galObj, showNav, galOrient) {
    $(galObj).each(function() {
        var cGalObj = $(this);

        //declaring gallery elements
        var bigImgWrap = $(cGalObj).find(".gal .story");
        var mask = $(cGalObj).find(".thumbnails");
        var thumbsWrap = $(cGalObj).find(".thumbs");
        var thumb = $(thumbsWrap).find("li");
        var prev = $(cGalObj).find(".navGal .prev");
        var nxt = $(cGalObj).find(".navGal .next");
        var capHtml = $(thumb).find(".description").html();
        var bigImgWrapEle = $(cGalObj).find(".dynamic");
        var agentVidDesc = $(cGalObj).find(".videoDetails");
        var btnG = $(cGalObj).find(".btn");
        var thumbW = $(thumb).width() + 10;
        var noOfThumbs = $(thumb).length;
        var thumbsWrapW = noOfThumbs * thumbW;
        var maskW = $(mask).width();
        var secMoveCount = 0;
        var noOfThumbSecsMoves = Math.floor(thumbsWrapW / maskW);

        //declaring Vertical controls
        var thumbH = $(thumb).height() + 10;
        var thumbsWrapH = noOfThumbs * thumbH;
        var maskH = $(mask).height();
        var noOfThumbSecsMovesV = Math.floor(thumbsWrapH / maskH);

        $(bigImgWrap).hide();
        $(bigImgWrap[0]).show();
        $(bigImgWrap).find(".description").html($(thumb).find(".description").eq(0).html());
        $(bigImgWrapEle).attr("src", $(thumb).find("a").eq(0).attr("href"));
        $(thumb[0]).parent().addClass('active');
        $(thumb).find("a").off("click");
        $(prev).off("click");
        $(nxt).off("click");
        $(prev).css("opacity", ".5");
        $(agentVidDesc[0]).show();
        $(agentVidDesc).addClass("active").html($(thumb).find(".description").eq(0).html());
        $(thumb[0]).addClass('active');

        if ($(cGalObj).hasClass("agentVideoGal")) {
            $(thumb).find("a").on("click", function() {
                $(thumb).removeClass('active');
                $(this).parent().addClass('active');
                capHtml = $(this).parent().find(".description").html();
                $(agentVidDesc).html(capHtml);
                $(bigImgWrapEle).attr("src", $(this).attr("href"));
                return false;
            });
            $(btnG).on('click', function(event) {
                event.preventDefault();
                if ($(agentVidDesc).hasClass("active") != true) {
                    $(agentVidDesc).addClass("active").fadeIn('fast');
                    $(this).css("background-position", "0px 0 ");
                } else {
                    $(agentVidDesc).removeClass("active").fadeOut('fast');
                    $(this).css("background-position", "-42px 0px");
                }
            });
        } else {
            $(thumb).find("a").on("click", function() {
                $(thumb).find('a').removeClass('active');
                $(this).parent().addClass('active');
                capHtml = $(this).parent().find(".description").html();
                $(bigImgWrap).find(".description").html(capHtml);
                $(bigImgWrapEle).attr("src", $(this).attr("href"));
                return false;
            });
        }

        var opcP = function() {
            if (secMoveCount > 0) {
                $(prev).css("opacity", "1");
            } else {
                $(prev).css("opacity", ".5");
            }
            if (secMoveCount < noOfThumbSecsMoves) {
                $(nxt).css("opacity", "1");
            } else {
                $(nxt).css("opacity", ".5");
            }
        }


        $(thumbsWrap).width(thumbsWrapW);
        if ($(cGalObj).hasClass("agentVideoGal") !== true) {
            $(thumbsWrap).height(thumbsWrapH);
        }

        if ($(cGalObj).hasClass("vertical")) {
            $(thumbsWrap).width("");
            var thumbsWrapH = noOfThumbs / 2 * thumbH;
            noOfThumbSecsMovesV = Math.floor(thumbsWrapH / maskH);
            $(prev).on('click', function(event) {
                var pos = $(thumbsWrap).position().top + maskH;
                if (secMoveCount > 0) {
                    $(thumbsWrap).animate({
                        'top': (pos)
                    }, 1000, opcP)
                    secMoveCount--
                }
                return false;
            });
            $(nxt).on('click', function(event) {
                var pos = $(thumbsWrap).position().top - maskH;
                if (secMoveCount < noOfThumbSecsMovesV) {
                    $(thumbsWrap).animate({
                        'top': (pos)
                    }, 1000, function() {
                        if (secMoveCount < noOfThumbSecsMovesV) {
                            $(nxt).css("opacity", "1");
                        } else {
                            $(nxt).css("opacity", ".5");
                        }
                        if (secMoveCount > 0) {
                            $(prev).css("opacity", "1");
                        } else {
                            $(prev).css("opacity", ".5");
                        }
                    })
                    secMoveCount++
                }
                return false;
            });
        } else {
            $(thumbsWrap).height("");
            $(prev).on('click', function(event) {
                var pos = $(thumbsWrap).position().left + maskW;
                if (secMoveCount > 0) {
                    $(thumbsWrap).animate({
                        'left': (pos)
                    }, 1000, opcP)
                    secMoveCount--
                }
                return false;
            });
            $(nxt).on('click', function(event) {
                var pos = $(thumbsWrap).position().left - maskW;
                if (secMoveCount < noOfThumbSecsMoves) {
                    $(thumbsWrap).animate({
                        'left': (pos)
                    }, 1000, function() {
                        if (secMoveCount < noOfThumbSecsMoves) {
                            $(nxt).css("opacity", "1");
                        } else {
                            $(nxt).css("opacity", ".5");
                        }
                        if (secMoveCount > 0) {
                            $(prev).css("opacity", "1");
                        } else {
                            $(prev).css("opacity", ".5");
                        }
                    })
                    secMoveCount++
                }
                return false;
            });
        }
    })
}

function validate() {
    $("#commentsForm").validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            captcha: "required"
        },
        messages: {
            firstname: "Please enter your name",
            email: "Please enter a valid email address",
            captcha: "Please enter code shown in the image"
        }
    });
    $("#ecForm").validate({
        rules: {
            name: "required",
            contact: "required",
            email: {
                required: true,
                email: true
            },
            message: "required",
            captcha: "required"
        },
        messages: {
            name: "Please enter your name",
            contact: "Please enter your conatct number",
            email: "Please enter a valid email address",
            message: "Please enter a message",
            captcha: "Please enter code shown in the image"
        }
    });
}

function mHover() {
    var item = $(".tabCont ul li");
    $(".mHover").css({
        "top": 0
    });
    $(item).each(function() {
        var cont = $(".mHover", this);
        $(this).hover(function() {
            $(cont).animate({
                "top": -151
            }, 300);
        }, function() {
            $(cont).animate({
                "top": 0
            }, 300);
        })
    })
}
$(document).ready(function() {
    vid();
    showHide();
    gallery(".photoGalD");
    gallery(".photoGalUpdate");
    gallery(".vidgal");
    gallery(".eventgal");
    validate();
    mHover();
    $(".carousel-demo").owlCarousel({
        items: 1,
        navigation: true,
        // Show next and prev buttons
        slideSpeed: 300,
        pagination: false,
        singleItem: true
    });
    $(".carousel-demo.artCar").owlCarousel({
        items: 1,
        navigation: true,
        // Show next and prev buttons
        slideSpeed: 300,
        pagination: false,
        singleItem: true
    });
    $(".agentCategories .tabCont ul").owlCarousel({
        items: 5,
        navigation: true,
        // Show next and prev buttons
        slideSpeed: 300,
        pagination: false,
        singleItem: false
    });
    $(function() {
        $('.scroll-pane').jScrollPane();
    });
});

I've been learning jQuery for the last 2 years without technical background or education. I want to know my level of coding and what I can do to improve and optimize it.

\$\endgroup\$
5
\$\begingroup\$

var per variable

It's personal preference, but it's a practical preference. If you had something like this in the middle of the code:

var vid = $(".videoBg"),
btn = $(".wVid"),
wrap = $(".home");

You would readily think "Oh, new variable vid and an assigment to existing variables btn and warp". But then you missed the commas. Also, it's easier to move around the variables if they have their own var.

Consider creating a jQuery plugin

gallery(".photoGalD");
gallery(".photoGalUpdate");
gallery(".vidgal");
gallery(".eventgal");

Not really that bad, but what if you could have done it like:

$('.class-common-to-gallery-elements').gallery()

Consider making it a jQuery plugin, no need to publish it online. jQuery plugins are, in leman's terms, self-contained, reusable units of code. Invest time learning how to make one.

Separate the config

I see you are using owlCarousel, but what if you needed more than just 3? Would you copy-paste the code? or just add a configuration, and all is set? I'd go for the latter, in this manner:

// Place configs here
var owlCarouselConfigs = {
  '.carousel-demo' : {
    items: 1,
    navigation: true,
    slideSpeed: 300,
    pagination: false,
    singleItem: true
  },
  '.carousel-demo.artCar' : {
    items: 1,
    navigation: true,
    slideSpeed: 300,
    pagination: false,
    singleItem: true
  },
  ...
}

// Execute
$.each(owlCarouselConfigs,function(selector,config){
  $(selector).owlCarousel(config);
});

Same could be applied to validate

Break apart code

Usually, in a jQuery plugin, I do this (see jQuery Boilerplate for the structure):

;(function ($, window, document, undefined) {

  // Plugin defaults
  var pluginName = "gallery",
    defaults = {
      propertyName: "value"
    };

  // Plugin constructor and prototype
  function Plugin(element, options) {
    // Configure instance properties and configurations
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    // Initialize the plugin
    this.init()
  }
  Plugin.prototype = {
    init: function () {
      // Here, I call out some stuff related to setups in UI, AJAX etc.
      this.setups();
      this.someMoreSetups();
    },
    // Functionality is broken off into their own functions
    setups: function () {
      // calling other functions in a function
      this.anAjaxFunction();
    },
    someMoreSetups: function () {...
    },
    anAjaxFunction: function () {...
    },
  };

  // Standard plugin stuff. Don't touch.
  $.fn[pluginName] = function (options) {
    this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName, new Plugin(this, options))
      }
    });
    return this
  }
})(jQuery, window, document);

$('.myElement').gallery();
\$\endgroup\$
  • \$\begingroup\$ I think most style-guides go for 1 var statement. \$\endgroup\$ – konijn Apr 15 '14 at 13:04
  • \$\begingroup\$ @konijn I thought it was cool too, until I move around variables and broke the code a lot. \$\endgroup\$ – Joseph Apr 15 '14 at 14:10
  • \$\begingroup\$ well I appreciate the help, thanks... but can you be more precise about what you want to convey... one of my friend suggested me to divide the whole gallery functions in to the chunks of code and keep them as seperate function and then call those functions Inside the gallery() with parameters and objects to pass through it... but I was unable to do that... can some one help with that \$\endgroup\$ – shaikhuu Apr 15 '14 at 14:10
  • 1
    \$\begingroup\$ @shaikhuu added how I do jQuery plugins. \$\endgroup\$ – Joseph Apr 15 '14 at 14:18
  • \$\begingroup\$ @Joseph the Dreamer yes u did but I m not that expert to understand it... reaching only intermediate level... needed guidance.... thanks for your answer... really appreciate your help.. \$\endgroup\$ – shaikhuu Apr 16 '14 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.