I have site that, in response to user interaction, dynamically creates divs using jquery. The div will have a span inside containing a timestamp to show its creation time, and the user can click a button to show or hide the timestamp span.
I ran into the issue of, when the user selects to hide timestamps, how do you prevent future dynamically added spans from showing? In reference to this question Create a CSS rule / class with jQuery at runtime, I added a style tag in the head dynamically. However, I also intended to allow the user to be able to choose a font from a drop down list and change the font style of the text inside the divs. Following this method now seems like it would create a lot of overhead.
Both issues revolve around the same issue: change already existing element and any future dynamically created matching element's css style, but I'm not sure the method mentioned above is really the best solution?
EDIT: SNIPPET
$(function() {
$('#add').click(function() {
$('#display').append("<div><span class='time'> ex. Timestamp</span> Div text contents...</div>");
});
$('#hidetime').click(function() {
$(this).text(function(i, text) {
if (text === "Hide Time") {
$("<style>").prop("type", "text/css")
.html(".time {display: none}").appendTo("head");
return "Show Time";
} else {
$('style').remove();
return "Hide Time";
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>Add</button>
<button id='hidetime'>Hide Time</button>
<div id='display'>
</div>