Question Edited:
So, probably i didn’t asked the question in the best way:
With X being the class name from the divs:
function functionName(X) {
$('h2.X').click(function(){
$(this).parent().find('div.X').slideToggle("slow");
});
<h2 class="divName" onclick="functionName(X)">Title</h2>
<div class="divName">
<p> description </p>
</div>
<h2 class="divName2" onclick="functionName(X)">Title</h2>
<div class="divName2">
<p> description </p>
</div>
Well, for those who don’t understand, just don’t downvote. Thanks a lot :/
Let’s put it this way:
$('h2.divName').click(function(){
$(this).parent().find('div.divName').slideToggle("slow");
});
<h2 class="divName">Title</h2>
<div class="divName">
<p> description </p>
</div>
<h2 class="divName2">Title</h2>
<div class="divName2">
<p> description </p>
</div>
<h2 class="divName3">Title</h2>
<div class="divName3">
<p> description </p>
</div>
I want to replicate the accordeon to function with all the divs…
I suggest you have a good read of the documentation for jQuery as I think you are missing the point.
Given the following markup:
You could write something like this:
What you are doing here is creating an event handler for all h2 elements that trigger the visibility of the next div.
This would allow you to do what you want whilst keeping Javascript out of your page which is very much what you should strive to do.
The recommended way to do this now though would be to use event delegation and reduce the number of event handlers and therefore memory usage.
Rewriting your markup as follows:
Will allow you to write code like this:
Which is really simple to write. What’s going on here is that jQuery is creating only one eventHandler per each instance of a div with the class
accordionon the page.That eventHandler is listening for any click events bubbling up from its children and if one of them is a h2 element then it will pass the context of that function to that element and toggle the visibility of that next div.
It’s really important to try to understand what you are doing when you are writing Javascript and really learn the basics. Javascript is the most important language in the web and should be treated as a first class language.