novicePrgrmr
novicePrgrmr

Reputation: 19405

Why won't Javascript code work after moving it from html to an external js file?

I have this Javascript code that was working perfectly fine in my HTML. When I moved it to my main.js it suddenly stopped working.

Disclaimer: I am very new to jQuery and Javascript, so sorry if it is really obvious.

var infoVisible = false,
buyVisible = false;

function closeAllProductInfo() {
    $('#info').css({visibility: 'hidden'});
    $('#buy').css({visibility: 'hidden'});
    $('#options.info a').removeClass('active');
    $('#options.buy a').removeClass('active');
    infoVisible = false;
    buyVisible = false;
    imagesVisible = false;
}

function openProductInfo() {
    closeAllProductInfo();
    $('#info').css({visibility: 'visible', opacity: 0});
    $('#info').animate({opacity: 1}, 250);
    $('#options.info a').addClass('active');
    infoVisible = true;
}

function openProductBuy() {
    closeAllProductInfo();
    $('#buy').css({visibility: 'visible', opacity: 0});
    $('#buy').animate({opacity: 1}, 250);
    $('#options.buy a').addClass('active');
    buyVisible = true;
}

$('.info').click(function() {
    if (infoVisible) { 
        $('#info').animate({opacity: 0}, 250, function() {  
            closeAllProductInfo(); 
        }); 
    } else { 
        openProductInfo(); 
    }

    return false;
});

$('.buy').click(function() {
    if (!$(this).hasClass('in-active')) {
        if (buyVisible) { 
            $('#buy').animate({opacity: 0}, 250, function() { 
                closeAllProductInfo(); 
            }); 
        } 
        else { 
            openProductBuy(); 
        }
    }

    return false;
});

$('#info').click(function() {
    if (infoVisible) { 
        $('#info').animate({opacity:0}, 250, function() { 
            closeAllProductInfo(); 
        }); 
    }
});

$('#buy').click(function() {
    if (!$(this).hasClass('in-active')) {
        if (buyVisible) { 
            $('#buy').animate({opacity:0}, 250, function() { 
                closeAllProductInfo(); 
            }); 
        }
    }
});

Upvotes: 1

Views: 1406

Answers (2)

Yoann
Yoann

Reputation: 3070

Try to wrap all your code in :

$(document).ready(function(){
   // Your code in here.
}); 

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39307

Probably because it used to execute after the document was loaded but now it executes when the script is loaded. Do you load main.js at the end of your HTML file or the start? Use this to get it to execute after the document is ready:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Upvotes: 1

Related Questions