Skip to content

Instantly share code, notes, and snippets.

@BryanYang
Last active September 13, 2018 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BryanYang/93c39f7d783ac0a8b33e6afeeb2b8790 to your computer and use it in GitHub Desktop.
Save BryanYang/93c39f7d783ac0a8b33e6afeeb2b8790 to your computer and use it in GitHub Desktop.
record user action with MutationObserver
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<style>
.cls1 {
color: black;
}
.flex {
display: flex;
}
#container {
border: 1px solid coral;
height: 500px;
margin-right: 100px;
flex: 1;
}
#play-ground {
border: 1px solid green;
height: 500px;
flex: 1;
}
#replay {
background: green;
color: white;
}
</style>
<script>
var index = 1;
var mutationList = [];
$(function () {
const mm = $('#mutationMount');
var mutationObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
console.log(mutation);
mutationList.push(mutation);
mm.text(mutationList.length);
});
});
mutationObserver.observe(document.getElementById('container'), {
attributes: true,
characterData: true,
childList: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
});
$('#addDiv').click(function () {
var name = prompt("Please enter your name", index)
var d = $('<div>', {
Class: 'cls1',
text: name
});
var dl = $('<input type="button" value="delete"/>');
dl.on('click', function () {
d.remove();
})
d.append(dl);
index++;
$('#container').append(d);
})
$('#setColor').click(function () {
$('.cls1')[0].style.color = 'red';
setTimeout(function() {
$('.cls1')[1].style.color = 'red';
}, 1000)
})
$('#replay').click(function () {
const container = $('#container');
mutationObserver.disconnect();
container.html('');
var interval = setInterval(function () {
if (mutationList.length) {
var m = mutationList.shift();
mm.text(mutationList.length);
switch (m.type) {
case 'childList':
if (m.addedNodes.length) {
m.addedNodes.forEach(n => {
m.target.appendChild(n)
})
}
if (m.removedNodes.length) {
m.removedNodes.forEach(n => {
m.target.removeChild(n);
})
}
break;
case 'attributes':
if(m.attributeName == 'style') {
}
default:
break;
}
} else {
clearInterval(interval);
}
}, 1000)
})
})
</script>
</head>
<body>
<div>
<input type="button" value="addDiv" id="addDiv" />
<input type="button" value="setColor" id="setColor" />
<input type="button" value="replay" id="replay" />
<span id="mutationMount"></span>
</div>
<hr />
<div class="flex">
<div id="container">
</div>
</div>
<hr />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment