Georgescu Rares Daniel
Georgescu Rares Daniel

Reputation: 119

javascript global variable good practice

I have a few variables pertaining to the height of elements an want to update them using $(window).on('resize'[...]), as well as calculate them when first loading the page so naturally I would rather make a function for doing that, instead of repeating the code.

Is it bad practice to make these variables global so that I can update them with a function, or is there any other way to do this?

    var hSum = 0
    for (var i = 0; i < content.length; i++) {
        var contentH = $(content[i]).height()
        hSum += contentH
    }

    var windowHeight = $(window).height(),
        footerHeight = footer.height(),
        heightDocument = windowHeight + hSum + footer.height() - 20;

This is the entirety of the script

function scrollFooter(scrollY, footerHeight) {

    if (scrollY >= footerHeight) {
        $('footer').css({
            'bottom': '0px'
        });
    } else {
        $('footer').css({
            'bottom': '-' + footerHeight + 'px'
        });
    }
}

$(document).ready(function() {
    var content = $('.content'),
        header = $('header'),
        footer = $('footer'),
        headerContainer = header.find('.container'),
        headerBackground = header.find('.background'),
        nav = $('.navbar')

    var hSum = 0
    for (var i = 0; i < content.length; i++) {
        var contentH = $(content[i]).height()
        hSum += contentH
    }

    var windowHeight = $(window).height(),
        footerHeight = footer.height(),
        documentHeight = windowHeight + hSum + footer.height() - 20;


    $('#scroll-animate, #scroll-animate-main').css({
        'height': documentHeight + 'px'
    })

    $('header').css({
        'height': windowHeight + 'px'
    })

    $('.wrapper-parallax').css({
        'margin-top': windowHeight + 'px'
    })

    scrollFooter(window.scrollY, footerHeight);

    setTimeout(function fadeHeaderIn() {
        headerContainer.css('opacity', '1')
        headerBackground.css('transform', 'scale(1.25, 1.25)')
    }, 300)


    $(window).on('scroll', function() {
        scroll = window.scrollY

        $('#scroll-animate-main').css({
            'top': '-' + scroll + 'px'
        });

        scrollFooter(scroll, footerHeight);

        nav.toggleClass('hidden', scroll < windowHeight)
    })

    nav.on("mouseenter", function() {
        nav.removeClass('minimized')
    })

    nav.on("mouseleave", function() {
        nav.addClass('minimized')
    })

    $('.navbutton').on('click', function(event) {
        if ($(this).attr('href') == "#contact")
            $('html, body').stop().animate({ scrollTop: documentHeight }, 300, 'swing')
        else $('html, body').stop().animate({ scrollTop: $($(this).attr('href')).offset().top }, 300, 'swing')
        event.preventDefault()

    })
})

Upvotes: 0

Views: 414

Answers (1)

Ahmed Gaafer
Ahmed Gaafer

Reputation: 1661

The best thing to do is to create a class to handle all the element functions.

for example, let's assume that you have a div or a canvas that you want to check for it's size.

function divHandler(divID){
  this.div = document.getElementById(divID);
  
  //Add all global variables here
  this.boundingRect = this.div.getBoundingClientRect()
}

//After that access the variables by other functions

divHandler.prototype.displayData = function(){
  console.log(this.boundingRect);

}

const d = new divHandler('someDiv');

d.displayData();
#someDiv{
  min-width: 100px;
  min-height: 100px;
  border: 1px solid black;
}
<div id="someDiv">

</div>

Now you have a class that controls all divs by id and you can use it again and again for all other divs in the code.

Update 1:

You can also add an event listener like this

function divHandler(divID){
  this.div = document.getElementById(divID);
  
  //Add all global variables here
  this.boundingRect = this.div.getBoundingClientRect()
}

divHandler.prototype.listen = function (event, cb, ...args){
  this.div.addEventListener(event,cb.bind(this, ...args));
}

const d = new divHandler('someDiv');

d.listen('click', function(e){
  console.log(e.type);
  this.div.style.backgroundColor = "blue"
});
#someDiv{
  min-width: 100px;
  min-height: 100px;
  border: 1px solid black;
}
<div id="someDiv"></div>

Upvotes: 2

Related Questions