$(document).ready(function() {
$('a#li-div1').click(function () {
$('#div1').slideToggle();
});
$('a#li-div2').click(function () {
$('#div2').slideToggle();
});
$('a#li-div3').click(function () {
$('#div3l').slideToggle();
});
});
Refactorings
No refactoring yet !
Jannik Nilsson
December 6, 2010, December 06, 2010 10:59, permalink
Try something like this:
<ul id="menu"><li><a href="#" data-rel="div1">Text</a></li>
Then you can do this:
$(function () {
$('#menu li a').click(function ()
{
$($(this).attr('data-rel')).slideToggle();
}
});
paul.wilkins.myopenid.com
December 6, 2010, December 06, 2010 11:02, permalink
You can use the attribute-starts-with selector
http://api.jquery.com/attribute-starts-with-selector/
The triggered function will run in the context of the matching element, which could be the "li-div3" element. That allows us to get the element using the this keyword.
Once we have the element, we can get its id, and then take the part of that id which starts from the third character which gives us the appropriate div, "div3"
Here I presume that the "div31" in the original post was a typing mistake, and should instead be "div3"
jQuery(function ($) {
$('a[id^="li-div"]').click(function () {
$('#' + this.id.substring(3)).slideToggle();
});
});
Adam
December 6, 2010, December 06, 2010 20:38, permalink
I don't know that this really gains you anything, but...
var TOGGLEABLE_ELEMENTS = {
'a#li-div1': 'div1',
'a#li-div2': 'div2',
'a#li-div3': 'div3l'
};
$(document).ready(function() {
$.each(TOGGLEABLE_ELEMENTS, function(li, div) {
$(li).click($(div).slideToggle);
});
});
Hi,
I have a menu panel and when you click a link, a div with a certain id slides down and so on. Is there an easier way to do this?
Thanks