I'm building a custom widget system for an app I'm working on. What I want to have happen is the ability for one widget to update another widget by changing out the data attributes value. On page load, the initial data is loaded into this data-attr via PHP and using jQuery to switch out the data after the fact.
For instance, one widget would work as follows:
- PHP loads json data into DOM element
- jQuery function is passed the elements ID and retrieves data from
data-attrand uses it to produce a graph for example - Based on user interaction, another widget sends data to element's
data-attrwhile also firing a custom jQuery event - Initial function gets the new data and updates it's graph
I've started a demo:
// Ranomize Number & Replace Variable
$(function() {
$('#random').click(function(e) {
e.preventDefault();
num = Math.random() + 100;
$('#data').attr('data-receiver', num);
});
});
// Receive Data & Output
$(function() {
var output = $('#output');
var received = $('#data').attr('data-receiver');
output.html(received);
// Not sure what to do next
});
#content {
background: #efefef;
margin: 40px auto;
display: block;
padding: 50px;
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div id="data" data-receiver="10"></div>
<strong>Output:</strong>
<span id="output"></span>
<br/>
<br/>
<a href="#" id="random">Randomize</a>
</div>
But to be honest I'm not sure how to start. I have some code putting a random value into the receiving DOM element, but not sure how to setup the event or write another function to receive and update the #output div.
I'm happy to answer questions or write more code to help better explain my goal. Thanks in advance.
sender()andreceiver()to send and receive data from the DOM element, which one do I place as thecallbackFunction?sender_func( trigger event ) -> DOM element data-attr -> receiver_func( gets data when trigger occurs ). So there is one element in the middle. The idea is that I will build a view, the function on the receiver side will get data on load, IF it's data ever gets updated, it then gets the new data and does what it needs. If it doesn't ever get data, then it never changes.