Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortening my jQuery

How would I make this jQuery shorter? I assume there must be a better way of working than this!?

(bare in mind I am new to jQuery)...

<script>
jQuery(function() {
    var White = jQuery("#white").hide();
    jQuery("#firstpagename").on("click", function() {
        White.toggle();
    });
});
</script>
<script>
jQuery(function() {
    var Black2 = jQuery("#v2black").hide();
    jQuery("#secondpagename").on("click", function() {
        Black2.toggle();
    });
});
</script>
<script>
jQuery(function() {
    var Black3 = jQuery("#v3black").hide();
    jQuery("#thirdpagename").on("click", function() {
        Black3.toggle();
    });
});
</script>

Any help or directions would be greatt as I am down to the last step on this site and want it finished :)

like image 898
Owen O'Neill Avatar asked Feb 27 '12 22:02

Owen O'Neill


1 Answers

You could use some extra data attribute and an extra class on your links to make it a little shorter.

So let's say your html looks like this:

<div id="white">white</div>
<div id="v2black">v2black</div>
<div id="v3black">v3black</div>

<div id="firstpagename"  class="toggle" data-for="white">toggle white</div>
<div id="secondpagename" class="toggle" data-for="v2black">toggle v2bacl</div>
<div id="thirdpagename"  class="toggle" data-for="v3black">toggle v3black</div>

then your jquery can rewritten like this:

jQuery(function() {
  $('.toggle').on('click', function() {
    var id = $(this).attr('data-for');
    $('#' + id).toggle();
  });
});
like image 181
Koen Peters Avatar answered Sep 30 '22 01:09

Koen Peters