so i implemented a bit of jQuery that basically toggles content via a slider that was activated by an <a> tag. now thinking about it id rather have the DIV thats holding the link be the link its self.
the jQuery that i am using is sitting in my head looks like this:
<script type="text/javascript">
function slideonlyone(thechosenone) {
$('.systems_detail').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
i was using this as a index type box so there are several products when you click on the <a> tag that used to be an image* it would render a bit of content beneath it describing the products details:
<div class="system_box">
<h2>BEE Scorecard database</h2>
<p>________________</p>
<a href="javascript:slideonlyone('sms_box');"></a>
</div>
the products details are wrapped in this div.
<div class="systems_detail" id="sms_box">
</div>
so when you click on what used to be a image* it would run the slideonlyone(‘div_id_name’) function. the function above then first closes all the other divs with the class name ‘system details’ and then opens/slides the div with the id that was passed into the slideonlyone function. that way you can toggle products details and not have them all showing at once.
note i only kept the <a> tag to show you what was in there i will be getting rid of it.
note: i had an idea of just wrapping the whole div in an <a> tag but is that good practice?
So now what i am wondering is since you need JavaScript to run onclick on a div tag how do you write it so that it still runs my slideonlyone function?
Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the
divelement with theonclickattribute like so:However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery’s
on()method or its shorthandclick(). For example:Inside your handler function (e.g.
slideonlyone()in this case) you can reference the element that triggered the event (e.g. thedivin this case) with the$(this)object. For example, if you need its ID, you can access it with$(this).attr('id').EDIT
After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the
divwith a data-attribute like so:To access the element’s data-attribute you can use the
attr()method as in @fmsf’s example, but the best practice is to use jQuery’sdata()method like so:Note how
data-targetis accessed withdata('target'), without thedata-prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element’s data object.