Reputation: 103
I have a simple DIV and can't get it to hide() and show().
I guess I am doing it right but can not find what is wrong with it.
<div id="thediv" >hola</div>
<input type="button" value="click to show">This is the div content</input>
$(document).ready(function() {
$("div#thediv").hide();
alert($("div#thediv").hide().attr("id"));
});
$("button").click( function() {
$("div#thediv").show();
alert('click');
});
Also, I created a fiddle at link"http://jsfiddle.net/rt9Fc/".
Any ideas?
Upvotes: 5
Views: 82243
Reputation: 3267
There is more proper 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:
$function()
is an alias to document.ready, it's faster to write and less bytes to send over the network :)Probably you wanted to have this:
HTML:
<div id="thediv">
hola
<input type="button" value="click to show"/>
</div>
That way we can optimise JavaScript:
$(function() {
var $myDiv = $("#thediv");
$myDiv.hide();
alert($myDiv.attr("id"));
$myDiv.find("input[type=button]").on('click', function() {
$myDiv.show();
alert('click');
});
});
Upvotes: 5
Reputation: 440
Give an id to button
<div id="thediv">hola</div>
<input type="button" id="btn" value="click to show"/>
Use this Code
$(document).ready(function() {
$("div#thediv").hide();
alert($("div#thediv").attr("id"));
});
$("input#btn").click( function() {
$("div#thediv").show();
alert('click');
});
Upvotes: 0
Reputation: 17366
Change button selector
: as you were using simple <input type='button'/>
still if you want to use $('button')
change your markup to <button></button>
$("#thediv").hide();
alert($("div#thediv").hide().attr("id"));
$("input[type='button']").click( function() {
$("#thediv").show();
});
DEMO -->
JsFiddle
Upvotes: 2
Reputation: 44740
put your click handler inside document.ready and change your selector to $("input:button")
-
$(document).ready(function () {
$("div#thediv").hide();
alert($("div#thediv").hide().attr("id"));
$("input:button").click(function () {
$("div#thediv").show();
alert('click');
});
});
Demo --->
JsFiddle
Upvotes: 10
Reputation: 123739
Change your button selector to :button
or use input. button
selector is used for <button>Somebutton</button>
$(document).ready(function() {
var $thediv = $('#thediv').hide(); //Cache the object here. Also you can shain it through
$(":button").click( function() {
$thediv.show();
alert('click');
});
});
If you have id, don't prefix it with tagname. it will make the selector slower. So just use #thediv
instead of div#thediv
. Also try to cache the jquery object to a variable if you are using it in multiple places, this will avoid calling the jquery object creation everythime.
Upvotes: 1