最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery With WebSocket - Stack Overflow

programmeradmin0浏览0评论

I have a little confusion in the following snippet. I am trying to make a jQuery drop effect with user input data. This is working but only the first value given stays for rest of the click.

Here are the snippets

index.html

<!DOCTYPE html>
<html>
<head>
<title>Pretech blog testing web sockets</title>

<script type="text/javascript" src=".1.3/jquery.min.js"></script>

      <script type="text/javascript" src=".11.3/jquery-ui.min.js"></script>
    <script type="text/javascript">
        var webSocket = new WebSocket('ws://localhost:8080/jqueryWebTest/websocket2');

        webSocket.onerror = function(event) {
            onError(event)
        };

        webSocket.onopen = function(event) {
            onOpen(event)
        };

        webSocket.onmessage = function(event) {
            onMessage(event)
        };

        function onMessage(event) {
            alert(event.data);
            document.getElementById('messages').innerHTML += '<br />'                    + event.data;
           // var myDiv = document.getElementById('dropDiv');
           // document.createElement(myDiv);

            $(function() {
                setTimeout (function() {
              var $dropDiv = $('#dropDiv');
              var mythis = $('#holder a');
              // get position of the element we clicked on
              var offset = mythis.offset();

              // get width/height of click element
              var h = mythis.outerHeight();
              var w = mythis.outerWidth();

              // get width/height of drop element
              var dh = $dropDiv.outerHeight();
              var dw = $dropDiv.outerWidth();

              // determine middle position
              var initLeft = offset.left + ((w/2) - (dw/2));

              // animate drop
              $dropDiv.css({
                      left: initLeft,
                      top: $(window).scrollTop() - dh,
                      opacity: 0,
                      display: 'block'
                  }).animate({
                      left: initLeft,
                      top: offset.top - dh,
                      opacity: 1
                  }, 300, 'easeOutBounce');
             },1500);
            });

        }

        function onOpen(event) {
            document.getElementById('messages').innerHTML = 'Now Connection established';
        }

        function onError(event) {
            alert(event.data);
        }

        function start() {
            var text = document.getElementById("userinput").value;

            webSocket.send(text);
            return false;
        }
    </script>

    <script type="text/javascript">



</script>

<style type="text/css">

#holder {
 position: absolute;
 top: 200px;
 left: 100px;   
}

#dropDiv {
 display: none;
 position: absolute;
 top: -20px;
 background: #ccc; 
}


</style>
</head>
<body>

 <div>
        <input type="text" id="userinput" /> <br> <input type="submit"
            value="Send Message to Server" onclick="start()" />
    </div>
<div id="messages"></div>
<div id="holder"><a href="javascript:void(0);" id="main">Which ring?</a></div>

<div id="dropDiv">The one ring to rule them all. </div>
<div id="dropDiv">The one ring to rule them all. </div>
</body>
</html>

websocket2.java

package .test.websockets;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.SendResult;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket2")
public class WebSocketTest2 {

    @OnMessage
    public void onMessage(String message, Session s) throws IOException,InterruptedException {

        System.out.println(message);

       // session.getBasicRemote().sendText(message);

        for (Session session : s.getOpenSessions()) {
            session.getBasicRemote().sendText("<div id='dropDiv'>"+message+" </div>");           }

        // Sending message to client each 1 second

    }

    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }

    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}

What would be a solution?

I have a little confusion in the following snippet. I am trying to make a jQuery drop effect with user input data. This is working but only the first value given stays for rest of the click.

Here are the snippets

index.html

<!DOCTYPE html>
<html>
<head>
<title>Pretech blog testing web sockets</title>

<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script type="text/javascript" src="https://ajax.googleapis./ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
    <script type="text/javascript">
        var webSocket = new WebSocket('ws://localhost:8080/jqueryWebTest/websocket2');

        webSocket.onerror = function(event) {
            onError(event)
        };

        webSocket.onopen = function(event) {
            onOpen(event)
        };

        webSocket.onmessage = function(event) {
            onMessage(event)
        };

        function onMessage(event) {
            alert(event.data);
            document.getElementById('messages').innerHTML += '<br />'                    + event.data;
           // var myDiv = document.getElementById('dropDiv');
           // document.createElement(myDiv);

            $(function() {
                setTimeout (function() {
              var $dropDiv = $('#dropDiv');
              var mythis = $('#holder a');
              // get position of the element we clicked on
              var offset = mythis.offset();

              // get width/height of click element
              var h = mythis.outerHeight();
              var w = mythis.outerWidth();

              // get width/height of drop element
              var dh = $dropDiv.outerHeight();
              var dw = $dropDiv.outerWidth();

              // determine middle position
              var initLeft = offset.left + ((w/2) - (dw/2));

              // animate drop
              $dropDiv.css({
                      left: initLeft,
                      top: $(window).scrollTop() - dh,
                      opacity: 0,
                      display: 'block'
                  }).animate({
                      left: initLeft,
                      top: offset.top - dh,
                      opacity: 1
                  }, 300, 'easeOutBounce');
             },1500);
            });

        }

        function onOpen(event) {
            document.getElementById('messages').innerHTML = 'Now Connection established';
        }

        function onError(event) {
            alert(event.data);
        }

        function start() {
            var text = document.getElementById("userinput").value;

            webSocket.send(text);
            return false;
        }
    </script>

    <script type="text/javascript">



</script>

<style type="text/css">

#holder {
 position: absolute;
 top: 200px;
 left: 100px;   
}

#dropDiv {
 display: none;
 position: absolute;
 top: -20px;
 background: #ccc; 
}


</style>
</head>
<body>

 <div>
        <input type="text" id="userinput" /> <br> <input type="submit"
            value="Send Message to Server" onclick="start()" />
    </div>
<div id="messages"></div>
<div id="holder"><a href="javascript:void(0);" id="main">Which ring?</a></div>

<div id="dropDiv">The one ring to rule them all. </div>
<div id="dropDiv">The one ring to rule them all. </div>
</body>
</html>

websocket2.java

package .test.websockets;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.SendResult;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket2")
public class WebSocketTest2 {

    @OnMessage
    public void onMessage(String message, Session s) throws IOException,InterruptedException {

        System.out.println(message);

       // session.getBasicRemote().sendText(message);

        for (Session session : s.getOpenSessions()) {
            session.getBasicRemote().sendText("<div id='dropDiv'>"+message+" </div>");           }

        // Sending message to client each 1 second

    }

    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }

    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }
}

What would be a solution?

Share Improve this question edited Jul 27, 2017 at 10:17 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Apr 30, 2015 at 7:56 ARNAB2012ARNAB2012 4002 gold badges5 silver badges19 bronze badges 2
  • Might be something to do with your setTimeout function not giving enough time for the input value to update after being clicked. It's tough to say without a working example. Can you further explain 'This is working but only the first value given stays for rest of the click' – Hunter Frazier Commented May 1, 2015 at 5:12
  • when a value(e.g. xyz ) is given in the input field and submit button clicked for the first time it gives "xyz" as dropdown animation effect . But if in the second time xyz changed into abc , it does not take abc as an animation effect string. it gives xyz as animation effect string. – ARNAB2012 Commented May 1, 2015 at 5:36
Add a ment  | 

2 Answers 2

Reset to default 2

try changing these:

<input type="submit" value="Send Message to Server" onclick="start()" />


function start() {
    var text = document.getElementById("userinput").value;
    webSocket.send(text);
    return false;
}

to:

<input id="submitButton" type="submit" value="Send Message to Server" />


function start() {
    var text = document.getElementById("userinput").value;
    webSocket.send(text);
    return false;
}

var subm = document.getElementById("submitButton");
subm.addEventListener("click", start, false);

I think its because you are using same Id for your dropDivs:

<div id="dropDiv">The one ring to rule them all. </div>
<div id="dropDiv">The one ring to rule them all. </div>

here :

  var $dropDiv = $('#dropDiv');
  var mythis = $('#holder a');

You excpect that all your dropDivs would get the drop annimation, Unfortunately only the first element with id "dropDiv" will be animated.

Try to use class instead for selecting your html elements.

发布评论

评论列表(0)

  1. 暂无评论