In my “update” pages I have often the need to call the same jQuery function both on page load and on click of some checkbox, mostly like this:
function foo(){
if ($('#mycheckbox').is(':checked')){
$('.myclass').hide();
} else {
$('.myclass').show();
}
}
$(function() {
foo(); // this is launched on load
$('#mycheckbox').click(function(){
foo(); // this is launched on checkbox click
})
});
On page load, the checkbox could be checked or not depending on database values: that’s why I have the need to launch the foo(); on load
Well, this works fine, but I always wondered if… there is a better or most elegant solution?
Thanks in advance
One way to do it (assuming that your site contains a server side code component) would be to hide/show the item in the server side render, as appropriate. This means that there is no screen ‘flicker’ (however slight it is) on load of the page.