Below is simple HTML form , there are two sets of controls on the page first set, second set.. The script for first set works perfectly fine for animation. How do I make that script generic for different kind of sets. Imagine I have 30 of these sets like this I need to do the animation, how do I pass the selector name as parameter to JQuery?
<!DOCTYPE html>
<html>
<head>
<style>
div { background:#def3ca; margin:3px; width:80px;
display:none; float:left; text-align:center; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<!-- first set -->
<button id="showr">Show</button>
<button id="hidr">Hide</button>
<div>who are you?</div>
<!-- second set -->
<button id="showr1">Show</button>
<button id="hidr1">Hide</button>
<div id="div1">how are you?</div>
<!-- script works on First set -->
<script>
$("#showr").click(function () {
$("div").first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
$("#hidr").click(function () {
$("div").hide(1000);
});
</script>
</body>
</html>
You should switch to classes. You can’t have multiple objects with the same id, but a class can be on multiple objects and then a single action in jQuery can operate on multiple objects. I’d suggest changing the HTML to this:
And, then the script can be like this:
By using
.closest()and making a container div and giving the target div for hide/show a class of it’s own, we make the jQuery code much more independent of the exact physical HTML so it doesn’t rely on there being nothing between elements.If you’re trying to make them all cascade so when you show the first one, it then (one at a time) shows all the other ones (regardless of how many there are), you could do that like this: