socket io mouse click event

给你一囗甜甜゛ 提交于 2020-01-11 06:47:10

问题


Does anyone know how to listen to the mouse events such as CLICK or HOVER so that when I click or hover any element it will happen the same in the second browser? Apologies for not including the code.

<script>
    // creating a new websocket
    var socket = io.connect('http://localhost:8000');

    // on message recived we print the new data inside the #container div
    socket.on('notification', function (data) {
        $("p").click(function () {
            alert("Hello");
            //or change the color
            $(this).css({"color": "red"});
        });

        var usersList = "<div id='aaa'>";
        $.each(data.users, function (index, user) {
            usersList += "<p>" + user.users + "</p>";
        });

        usersList += "</div>";
        $('#container').html(usersList);
    });
</script>
<p>Click me!</p>

回答1:


Client side:

In client side, you should first define an event listener for every type of event you need (using jQuery). In that listener, simply emit an socket.io event containing ID of element that triggered the event, so server can broadcast that to all other clients.

Also, if an event received from server, you should simulate that on it's corresponding element via jQuery.

$(document).on('click', function(event){
    socket.emit('myClick', {id: event.target});
}

var socket = io.connect('http://localhost');

socket.on('myClick', function (data) {
    $(data.id).trigger('click');
}

Server side:

In server side, just emit whatever event that was triggered, to all other clients except sender.

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
    socket.on('myClick', function (data) {
        socket.broadcast.emit('myClick', data);
    });
});


来源:https://stackoverflow.com/questions/19499597/socket-io-mouse-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!