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
Based on your example snippets of HTML, the following should work (it grabs the all
.contentdivs and works backwards to find the associatedspan):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.