Reputation: 6085
I would like each "p" element to show upon clicking the button. But it is not not working please help.
<script>
$(document).ready(function(){
$("p").hide();
$("button").click(function(){
$('p').each(function() {
//alert($(this).text());
var abc = $(this).text();
abc.next().show();
});
});
});
</script>
<button>Toggle</button>
<p>Hello</p>
<p>Good morning</p>
<p>Good after noon</p>
<p>Good evening</p>
<p>Good night</p>
<div></div>
Upvotes: 1
Views: 12735
Reputation: 111
Here is the javascript that will show one at a time with the HTML you have
var hiddenP = $("p:hidden");
var howMany = hiddenP.length;
var pIndex = 0;
$("button").click(function(evt){
if (pIndex == howMany)
return false;
$(hiddenP[pIndex]).fadeIn(1000);
pIndex +=1;
});
look at the example on jsfiddle to view the HTML and CSS http://jsfiddle.net/Cvm68/
Upvotes: 0
Reputation: 7525
$("p").hide();
$("button").click(function(){
$('p').each(function () {
if (!$(this).is(":visible")) {
$(this).show();
return false;
}
});
});
Upvotes: 7
Reputation: 10830
I would potentially extend it one step further: I assume your example is a reduced and simplified sample for easy conversation. If your application is to have a lot of DOM manipulation (ie. some elements could get destroyed and rebuilt) or if you run into timing issues surrounding the 'click' event being bound, I would use .delegate() to bind the click instead:
$(document).ready(function(){
$("p").hide(); // there are other ways to hide depending on your needs or to avoid FOUC
$("body").delegate("button", "click", function() {
$("p").show();
}
});
I chose "body" as the listener simply because I don't know your page contents. The best listener is the nearest parent that is at no risk of being destroyed, often a wrapper div of some sort. Swap out "body" for a more specific selector if you can.
Here's the difference:
.click() : "Grab this specific element and ask it to listen for clicks on itself." .delegate(): "Grab a parent-level object and ask it to listen for clicks on any element matching the designated selector."
.delegate() might be "overkill" for some purposes, but I use it whenever I can because it is much more future-proof.
Upvotes: 0
Reputation: 1449
Try using the below code:
$('p').each(function() {
$(this).show();
});
Or simply
$('p').show();
Hope this Helps!!
Upvotes: 0