user2468586
user2468586

Reputation: 13

Moving Javascript from the html to an external file

I am having trouble using some javascript that I am trying to convert from inline to an external javascript document. This code, that I'm trying to place externally does not work.

// JavaScript Document
function homepage() {
    $("#button").click(function(){
        $("#main, #nav").slideToggle();
        if($(this).html() == "-"){
            $(this).html("+");
            setTimeout(function() {
                $('#wrapper').css('top', 'auto');
                $('#wrapper').animate({ 'bottom': '0' }, 500);
            }, 500);
        } else {
            $(this).html("-");
            setTimeout(function() {
                $('#wrapper').animate({ 'top': '0' }, 500);
                $('#wrapper').css('bottom', 'auto');
            }, 500);
        }
    });
}

Upvotes: 0

Views: 274

Answers (3)

Zim84
Zim84

Reputation: 3497

Your code makes me assume that you are using jQuery. To move a JS file that uses a library like jQuery to an external file, you have to do the following steps:

If the code is inside jQuery and looks like this:

$(document).ready(function(){
    // here is all your code
});

Then you have to move all of it, including the $(document).ready(); part into the external file and (best) load it at the bottom of your html page.

Upvotes: 0

CastenettoA
CastenettoA

Reputation: 693

Tries to lock up the script so:

$(document).ready(function(){
  // JavaScript Document
  function homepage() {
  $("#button").click(function(){
  $("#main, #nav").slideToggle();
  if($(this).html() == "-"){
      $(this).html("+");
      setTimeout(function() {
        $('#wrapper').css('top', 'auto');
        $('#wrapper').animate({ 'bottom': '0' }, 500);
      }, 500);
  }
  else{
      $(this).html("-");

      setTimeout(function() {
          $('#wrapper').animate({ 'top': '0' }, 500);
          $('#wrapper').css('bottom', 'auto');
      }, 500);
  }
  });}

});

Upvotes: 1

user229044
user229044

Reputation: 239230

I assume that it "doesn't work" because your jQuery selectors are failing. Put your code inside as $(function () {...}) to insure it runs on DOM-ready.

Upvotes: 0

Related Questions