Reputation: 201
Currently, I have a DIV that, when you click on it, another DIV appears. Works fine. However, if I try to add the same id's down the page a bit to do the effect again, I get nothing. Here is my script:
<script>
$(document).ready(function(){
$("#click").click(function(){
$("#fade").fadeToggle();
});
});
</script>
and then in the HTML I have:
<div id="click">Click Here!
<div id="fade">CONTENT HERE
</div>
</div>
which I said, work fine, until I try to do it again. Is there a way to make it so I can do this as many times as I want without rewriting the script with different id's (there has to be a more efficient way than that)
Upvotes: 1
Views: 1115
Reputation: 148130
Use class instead of repeating ids and use class selector to bind the event and finding the element with class fade
withing the clicked element using context in selector.
<div class="click">Click Here!
<div class="fade">CONTENT HERE
</div>
</div>
</<script>
$(document).ready(function(){
$(".click").click(function(){
$(".fade", this).fadeToggle();
});
});
</script>div>
Upvotes: 1
Reputation: 3414
id="YOUR_ID_NAME" is a uniq id in your document.
if you want to reuse your jquery then you can use class
otherwise you can take multiple id in your jquery
Here is code :
$(document).ready(function(){
$("#click,#click1,#click2").click(function(){
$(".fade", this).fadeToggle();
});
});
<div class="click">Click Here!
<div id="fade">CONTENT HERE</div>
</div>
<div id="click1">Click Here!
<div class="fade">CONTENT HERE</div>
</div>
<div id="click2">Click Here!
<div class="fade">CONTENT HERE</div>
</div>
For better to use class for your document. If you want to reuse in your jquery.
$(document).ready(function(){
$(".click").click(function(){
$(".fade", this).fadeToggle();
});
});
<div class="click">Click Here!
<div id="fade">CONTENT HERE
</div>
</div>
Upvotes: 0
Reputation: 113385
The id has to be unique in a document. From documentation:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
Solution is to replace the #click
id with the .click
class:
HTML:
<div class="click">Click Here!
<div class="fade">CONTENT HERE</div>
</div>
jQuery:
$(document).ready(function(){
$(".click").click(function(){
$(".fade", this).fadeToggle();
});
});
Also #fade
id has to be replaced with .fade
class because you are selecting .fade
inside of clicked element (this
).
Upvotes: 1