Question

I'd like to learn how I can define a reference to the target element of any click event in a page to be stored in JSON (for transfer).

The solution shouldn't rely on using the class or id of the target.

Specifically, whenever an element (which may not have a class or id) is clicked in the page, I'm trying to define a reference to the targeted element that can be used stored in JSON format for transfer so that I can use the it in an identical page.


Example Usage:

This is a test where 2 or more users are working together in the same interface from different devices

  • A collaboration app that serves 2 users identical pages:

User 1:

<body>
    <div class="body-wrapper">
        <button>Click Here</button>
    </div>
    <div>
        <button>Click Me</button>
        <div>
             <button>Or Click Me</button>
        </div>
    </div>
</body>

User 2: (identical)

  • when the button "Click Me" is the target of a click event, the listener returns some kind of reference to that button that I can send over the web (Here's where the JSON format becomes necessary)

  • The outcome: I can echo the click on that button in User 2's DOM.


Edit:

As briefly discussed in the answer's comments, event delegation can be used to handle dynamically generated content. Is this the proper combination of this question's answer with event delegation?

$(document).on("mouseup mousedown click mousemove", function(e) {
    var element = e.target.index("body *");
    socket.emit("event", element, e);
});
Was it helpful?

Solution

If the DOM is identical on both pages, you can use the element's index in the DOM:

$("button").click(function() {
    var position = $(this).index("body *");
    // Send "position" to the server
    ...
}

On the receiving page, you can find the corresponding button with:

$("body *").eq(position);

The proper way to do the event delegation you asked about is:

$(document).on("mouseup mousedown click mousemove", "button,checkbox,option", function(e) {
    var element = $(this).index("body *");
    socket.emit("event", element, e);
});

Change the list of element types to all the ones that you need to catch clicks on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top