There is a more correct version of your code: JsFiddle
HTML:
<div id="thediv">hola</div> <input type="button" value="click to show"/>
JavaScript:
$(function() { var $myDiv = $("#thediv"); $myDiv.hide(); alert($myDiv.attr("id")); $("input[type=button]").on('click', function() { $myDiv.show(); alert('click'); }); });
Some useful notes:
- Search the cache of DOM beacuse elements that they find
- use instead of click, it works faster
- $ (function () is an alias for document.ready, it writes faster and has fewer bytes to send over the network :)
- you do not need to use div # id selectors, #id is enough for the beacuse identifier to be unique on your page, moreover, after jquery uses the javascript findElementById function, it will not need to do additional checking for the div.
- there is a good jQuery performance article: artzstudio
- the input should not be split into the open and close tag.
Perhaps you wanted to have this:
HTML:
<div id="thediv"> hola <input type="button" value="click to show"/> </div>
this way we can optimize JavaScript:
$(function() { var $myDiv = $("#thediv"); $myDiv.hide(); alert($myDiv.attr("id")); $myDiv.find("input[type=button]").on('click', function() { $myDiv.show(); alert('click'); }); });
source share