Nodejs - socket.io and jquery

Asked

Viewed 157 times

-1

Good afternoon

I’m following the initial socket.io tutorial and everything is working, but I don’t understand why jquery only works if you call the script in html

I tried to install by npm and it does not work (the message does not log)

I thought package.json served just so I didn’t have to call the script in html

Or to use by npm I should have taken the script from html, putting in a file the part?

Can you explain better how this works?

<!doctype html>
<html>
  <head>
    <title>Olá, Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function() {
      //load socket.io-client
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      });
    </script>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

1 answer

1


since you are using Node.js one option is to take it out of html and include it in a separate file and create a variable content the $ symbol used in jquery (don’t forget to have jquery included in your package.json or run the command npm install --save jquery

var $ = jQuery = require('jquery')(window);
  • ok, so it’s just because I’m opening tag script in the html file anyway? html doesn’t get what’s in package.json

  • in case it will create a conflict because they will have 2 jquerys 1 of the downloaded package through npm and another that you put in html (downloaded through a Cdn)

  • so I took the Cdn and installed it by npm, then it didn’t work anymore

  • Did you declare as a variable in a part file? your <script> tag will not really work, but since you are using Node.js you can take the script tag and include a file. js that contain the content of the script you want to run (npm installs bilbiotecas/packages that can only be called in javascript files)

  • no, I had not stated. I will change here to test this way. thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.