Question provoked as I wondered if I can just declare $(document).ready()
at the top of <script>
and write regular vanilla JS inside of it so that I don't have to declare $(document).ready()
everytime I use JQuery.
I also tested if JQuery can be used with JS locally (inside of '{}'). But it seems like below code doesn't work.
Can someone clarify on this please? Thank you.
<style>
#demoDiv {
width: 200px;
height: 200px;
border: 2px brown solid;
}
</style>
</head>
<body>
<div id='demoDiv'></div>
<br>
<button id='testButton' onclick='testFunc()'>Test</button>
<script>
$(document).ready(function() {
function testFunc() {
$('#demoDiv').style.display = 'none';
}
});
</script>
</body>
jQuery is a JavaScript library, so you can use jQuery with any other JavaScript functions.
Your particular example doesn't work for two reasons.
First, because .style
is a property of DOM objects and not jQuery objects.
You could extract a DOM object from the jQuery object:
$('#demoDiv')[0].style.display = 'none';
Or just consistently use the jQuery API:
$('#demoDiv').css("display", "none");
Second, because testFunc
is not a global so is out of scope for your inline event handler.
Use $('#testButton').on('click', testFunc)
instead.