William
William

Reputation: 1175

Function is not defined in an HTML file

So, I tend to make a script in html file FIRST then move it to a javascript file when I know it works... However, now it is returning a not defined.

Here is my html:

<div class="tab">
  <button class="tablinks" onclick="openAction(event, 'battle-wrapper')" id="defaultOpen">Battle</button>
  <button class="tablinks" onclick="openAction(event, 'tradeskill-wrapper')">Trade Skills</button>
  <button class="tablinks" onclick="openAction(event, 'crafting-wrapper')">Crafting</button>
</div>

Here is my javascript:

var storedUsername;

// Port Connect Cht
if (window.location.hostname == '****' || window.location.hostname == '****') {
  var port = 443;
} else {
  var port = 8080;
}

var connected = false;
var socket = io.connect(window.location.hostname + ':' + port, { 'connect timeout': 5000 });

// Connection Successful
socket.on('connect', function () {
  connected = true;
  // socket.emit('login');
});

socket.on('disconnect', function () {
  connected = false;
});

$(document).on('click', 'button#btn-logout', function () {
  socket.emit('logout');
});

socket.on('not logged', function (destination) {
  window.location.href = destination;
});

socket.on('start up', function (dataObj) {

});

$(document).ready(function (dataObj) {
  $('#battle-wrapper').on('click', 'button#battlebutton', function (event) {
    event.preventDefault();
    socket.emit('fight mob', $('#monster').val());
  });

  socket.on('mob test', function (dataObj) {
    if (dataObj.userStats) {
      $('#player-stats').html(dataObj.userStats);
      $('#mob-stats').html(dataObj.mobStats);
      $('#fight-results').html(dataObj.results);
      $('span#action-counter').html(dataObj.autos);
      $('#title').html(dataObj.autos + ' - KoG');
    } else {
      $('#title').html('AUTOS EXPIRED - KoG');
    }

  });

  $('#generalChat').click(function () {
    $('#chat').toggle();
  });

  var current = '#actions';

  // Actions Button Handler
  $('#btn-actions').click(function () {
    if (current != '#actions') {
      $(current).hide();
      current = '#actions';
      $(current).show();
    }
  });

  // Profile button handler
  $('#btn-profile').click(function () {
    if (current != '#profile') {
      $(current).hide();
      current = '#profile';
      $(current).show();
    }
  });

  // Kingom button handler
  $('#btn-kingdom').click(function () {
    if (current != '#kingodm-page') {
      $(current).hide();
      current = '#kingdom-page';
      $(current).show();
    }
  });

  // inventory button handler
  $('#btn-inventory').click(function () {
    if (current != '#inventory') {
      $(current).hide();
      current = '#inventory';
      $(current).show();
    }
  });

  //  allicne button handler
  $('#btn-alliance').click(function () {
    if (current != '#alliance') {
      $(current).hide();
      current = '#alliance';
      $(current).show();
    }
  });

  // mail button handler
  $('#btn-mail').click(function () {
    if (current != '#mail') {
      $(current).hide();
      current = '#mail';
      $(current).show();
    }
  });

  // Statistics Handler
  $('#statistic-row').load('statistics.ejs', function () {
    socket.on('time', function (data) {
      $('#time').html(data);
    });

    socket.on('users online', function (usersConnected) {
      $('#online').html(usersConnected);
    });
  });
});

// Chat Handler
$('#chat').load('chat.ejs', function () {

  $('#chat-form').submit(function (event) {
    event.preventDefault();

    var msg = $('#m').val();

    // Clears chat field
    $('#m').val('');

    // Discards message if not connected
    if (!connected || msg == '') {
      return false;
    }

    socket.emit('chat', msg, storedUsername);
  });

  // Populat chat
  socket.on('message', function (message, username) {
    storedUsername = username || storedUsername;
    $('#messages').prepend($('<li>').html(message));
  });

  // Get the element with id="defaultOpen" and click on it
  document.getElementById('defaultOpen').click();

  function openAction(evt, actionName) {
    // Declare all variables
    var i; var tabcontent; var tablinks;
    console.log(actionName);

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName('tabcontent');
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = 'none';
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName('tablinks');
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(' active', '');
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(actionName).style.display = 'block';
    evt.currentTarget.className += ' active';
  }
});

**THE RELEVANT FUNCTION IS AT THE END Now I know the script itself works when inside the html file. I am including my JS file correctly because it uses a lot of other things, and they work. But for some reason, this function is the only thing not working.

EDIT: Here is the full console error:

Uncaught ReferenceError: openAction is not defined
    at HTMLButtonElement.onclick (game:66)
    at HTMLDivElement.<anonymous> (game.js:152)
    at HTMLDivElement.<anonymous> (jquery.min.js:4)
    at Function.each (jquery.min.js:2)
    at r.fn.init.each (jquery.min.js:2)
    at Object.<anonymous> (jquery.min.js:4)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

EDIT: I added my whole JS file, maybe one of you can spot an error where I can't. I also added **** to things I wanted to censor.

Upvotes: 0

Views: 2696

Answers (2)

Chad Moore
Chad Moore

Reputation: 764

The problem is one of scope. You've defined your function openAction() inside another function starting with $('#chat').load('chat.ejs', function () { ..., your HTML has no access to that context.

Your HTML is expecting that to be a global, so move the definition of openAction() below the function that is currently enclosing it..

Upvotes: 3

dgeare
dgeare

Reputation: 2658

Provided I understand correctly: If everything works when they are part of a single file, but you get function not defined when you relocate the script to a separate file then the issue is likely one of ordering/sequencing.

you can load the external script before the function invocation (this works because scripts are parser blocking and it will evaluate the file before the script block that follows it)

<div class="tab">
  <button class="tablinks" onclick="openAction(event, 'battle-wrapper')" id="defaultOpen">Battle</button>
  <button class="tablinks" onclick="openAction(event, 'tradeskill-wrapper')">Trade Skills</button>
  <button class="tablinks" onclick="openAction(event, 'crafting-wrapper')">Crafting</button>
</div>

<script src='some_external_script_containing_openAction.js'></script>
<script>
  // Get the element with id="defaultOpen" and click on it
  document.getElementById('defaultOpen').click();
</script>

or you can place the triggering code in an onload handler (personal preference)...

<div class="tab">
  <button class="tablinks" onclick="openAction(event, 'battle-wrapper')" id="defaultOpen">Battle</button>
  <button class="tablinks" onclick="openAction(event, 'tradeskill-wrapper')">Trade Skills</button>
  <button class="tablinks" onclick="openAction(event, 'crafting-wrapper')">Crafting</button>
</div>

<script>
  //wait for all resources to load.
  window.addEventListener('load', function(e){
    // Get the element with id="defaultOpen" and click on it
    document.getElementById('defaultOpen').click();
  });
</script>
<script src='some_external_script_containing_openAction.js'></script>

But I don't quite have enough information to diagnose your problem for certain. If neither of these solutions are relevant to your situation, put a console.log('here') in your script file and make sure that it is firing in your page (F12 usually opens the console). if not you might have an issue with how you are linking to your file.

Upvotes: 0

Related Questions