I observed when I put the ready event the function works but as I remove it It does not..
Works.
<script type="text/javascript">
$(document).ready( function() {
$('.clicky').click( function() {
alert("TEst10");
$(this).addClass('clicked');
alert("TEst10");
setTimeout( function() {
$(this).removeClass('clicked');
}, 1000 );
});
});
</script>
Not work
<script type="text/javascript">
$('.clicky').click( function() {
alert("TEst10");
$(this).addClass('clicked');
alert("TEst10");
setTimeout( function() {
$(this).removeClass('clicked');
}, 1000 );
});
</script>
Why the second one does not work?
Because element with a class
clickyisn’t in the DOM structure when your second code gets called.The first one works because you wrapped the code in
document.readyfunction which gets invoked once the DOM is ready.If you want to make the second code work just put the code in the script tag after the definition of element with class
clicky, preferably put the script at the end of thebodytag.But why not just use
document.ready?