-2

How can I optimize this sample snippet:

Note that it has multiple calls to locate the #data and #click tags.


$(function(){
    $('#data').hide();
    $('#click').click(function() {
      $('#data').toggle('', function() {
      });
    $('#click').hide();
    });
})

NotMe
  • 87,343
  • 27
  • 171
  • 245
Cheerio
  • 1,260
  • 6
  • 19
  • 37
  • 6
    What problems are you currently experiencing with this code that might require optimization? What kind of optimization do you require: code shortening or some performance? – Darin Dimitrov Jul 08 '11 at 16:10
  • I'm looking for a new approach – Cheerio Jul 08 '11 at 16:11
  • Seems quite succinct if you ask me – Dan Hanly Jul 08 '11 at 16:11
  • 2
    @MiniNaim, new approach to do what? You haven't even explained what you are trying to achieve. It's kinda difficult to propose a new approach without knowing what you are trying to approach. – Darin Dimitrov Jul 08 '11 at 16:12
  • 1
    It's clear and simple, I want to display a hidden content when I click on a button. – Cheerio Jul 08 '11 at 16:13
  • 1
    @Darin: It's pretty obvious that he just wants to optimize the snippet of code that was posted. There is no deeper meaning to this question, if that's what you are looking for. – Chris Laplante Jul 08 '11 at 16:14
  • 1
    Sure, it might be obvious to anyone familiar with jQuery what he's trying to do; and that's only assuming he knows what he's doing. However, without describing what he's trying to achieve, it's not very helpful to the newbies. – Sparky Jul 08 '11 at 16:36

3 Answers3

4

Two less lines of code.

<style type="text/css">
 #data{display:none;}
</style>

<script>
$(function(){
    $('#click').click(function(){
       $('#data,#click').toggle();
    });
});
</script>

<div id="data">Some data</div>

<button id="click">Click me</button>
Mark Perry
  • 1,705
  • 10
  • 12
2

Sure.

$(function(){
    var data = $('#data');
    var click = $('#click');

    click.click(function() {
        data.toggle();
        $(this).hide();
    });
});

Cache your selectors in variables if you plan to use them later. Don't use jQuery for something you can accomplish with CSS. So instead of hiding data with data.hide() do it in your CSS with display:none.

See this question: jQuery Standards and Best Practice

Community
  • 1
  • 1
Radu
  • 8,561
  • 8
  • 55
  • 91
  • Could do `click.hide()` inside of the click callback? – Mark Perry Jul 08 '11 at 16:37
  • Shouldn't `click.hide()` here be inside the `click` handler? Otherwise it hides the '#click' element as soon as `$(document).ready()` is evaluated. I assume the OP wants the '#click' element to be hidden only on click (otherwise, how can I click it?). – nrabinowitz Jul 08 '11 at 16:56
1

Yes, there is no need to repeat $("#data") and $("#click") - assign them to variables and then reuse them. In you current code, it is having to locate the items twice.

Fiona - myaccessible.website
  • 14,481
  • 16
  • 82
  • 117