I am an absolute beginner in this field. I have written the following code but it’s not working. Can someone explain where is the error?
<script type="text/javascript">
$("button").click(function(){
$("div").show("slow");
});
</script>
<button>show</button>
<div style="min-height:300px; min-width:400px; border:10px solid grey; display:none;"></div>
<a href="http://#" style="display: none">this is a link</a>
You execute the jQuery before the button is there. So at the point jQuery is executed, the button is not existent.
The solution is to use
$(document).ready(...).All elements on a page (HTML) are parsed to the DOM of that page. The DOM is a hierarchical collection of all elements. You can select elements out of it using jQuery.
However, obviously the DOM needs to be fully there before you can select the elements. In your case, you first select the button, and create it afterwards. That does not work. At the time of the selector the button does not exist yet.
Using jQuery’s
$(document).ready(), you can defer the function containing selectors until the DOM is fully loaded and parsed – at which time the selector works because the elements are there.