Reputation: 8855
instead of re-writing the same function, I want to optimise my code :
<div class="header">
<h3>How to use the widget</h3>
<span id="idwidget" ></span>
</div>
<div class="content" id="widget">
the JS :
<script type="text/javascript">
$(document).ready(function() {
var showText="Show";
var hideText="Hide";
$("#idwidget").before(
"<a href='#' class='button' id='toggle_link'>"+showText+"</a>"
);
$('#widget').hide();
$('a#toggle_link').click(function() {
if ($('a#toggle_link').text()==showText) {
$('a#toggle_link').text(hideText);
} else {
$('a#toggle_link').text(showText);
}
$('#widget').toggle('slow');
return false;
});
});
</script>
This is working just with the div which is called widget and the button called idwidget.
But on this page i have also :
<div class="header">
<h3>How to eat APPLES</h3>
<span id="IDsomethingelse" ></span>
</div>
<div class="content" id="somethingelse">
And I want it to be compatible with the code.
I heard about children attribute, do you have an idea how to do that please ?
Thank you
Upvotes: 0
Views: 490
Reputation: 14873
Based on your example snippets of HTML, the following should work (it grabs the all .content
div
s and works backwards to find the associated span
):
<script type="text/javascript">
$(document).ready(function() {
var showText="Show";
var hideText="Hide";
$(".content").each(function() {
var $content = $(this).hide();
$("<a href='#' class='button' >"+showText+"</a>")
.insertBefore($("#id" + $content.attr("id")))
.click(function() {
if ($(this).text() == showText) {
$(this).text(hideText);
} else {
$(this).text(showText);
}
$content.toggle('slow');
return false;
});
});
});
</script>
Edit: I've compacted the code a little (but it now requires jQuery 1.4 for the .text(function)
bit).
Edit 2: Ok still more compact than the original, but back to 1.3.X safe code.
Upvotes: 1