55502f40dc8b7c769880b10874abc9d0

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

$(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 !

4c2dcafc3c9f39cc38d3443af9b62ecf

Jannik Nilsson

December 6, 2010, December 06, 2010 10:59, permalink

1 rating. Login to rate!

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();
	}
});
Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

December 6, 2010, December 06, 2010 11:02, permalink

1 rating. Login to rate!

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();
  });
});
A8d3f35baafdaea851914b17dae9e1fc

Adam

December 6, 2010, December 06, 2010 20:38, permalink

1 rating. Login to rate!

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);
    });
});

Your refactoring





Format Copy from initial code

or Cancel