0

I've used jQuery to open and close some divs.

The code works fine until I try to use it as a function, where, I think due to context / or scoping issues the jQuery(this) that I've been using as a selector doesn't work when executed from a function.

The function is this:

  function open_close_sections() {
     if(jQuery('.question').hasClass('open')) {
            jQuery(this).removeClass('open');
            jQuery(this).next().slideUp();             
            }
           else
           { 
             jQuery('.open').not(this).next().slideUp();
             jQuery('.open').not(this).removeClass('open');
             jQuery(this).addClass('open');
             jQuery(this).next().slideDown();
           }

  }

and I'm trying to invoke it with

jQuery('.question').click(open_close_sections());

You can see the code working outside of a function at this pen: http://codepen.io/amort2000/pen/KVqaqr and failing to work in a function at this pen: http://codepen.io/amort2000/pen/YwQNOQ

JJJ
  • 32,902
  • 20
  • 89
  • 102
amort2000
  • 1
  • 1
  • As per the linked dupe. jQuery's `click` is expecting a function reference - not the result of calling the function. Remove the parentheses. – Jamiec Jan 11 '16 at 17:24
  • how is this a duplicate of that question?? – martskins Jan 11 '16 at 17:25
  • You can use `bind` as well to bind the context. Also `jQuery('.question').click(open_close_sections());` should be `jQuery('.question').click(open_close_sections);` – Rajesh Jan 11 '16 at 17:26
  • @lascort How is it *not*? – JJJ Jan 11 '16 at 17:27
  • The question you marked as being a duplicate of does not address the major issue he's having with scope. I reckon though that after the scope problem is solved he will have to resort to that question. But I don't think that makes it a duplicate – martskins Jan 11 '16 at 17:34
  • @lascort There is no issue with scope. jQuery binds the `this` reference to the function automatically. Once the parentheses are removed it works correctly. – JJJ Jan 11 '16 at 17:37
  • @Juhana let me downvote myself to oblivion – martskins Jan 11 '16 at 17:39

1 Answers1

0
jQuery(document).ready(function() {
  function open_close_sections(x) {
    if (jQuery(x).hasClass('open')) {
      jQuery(x).removeClass('open');
      jQuery(x).next().slideUp();
    } else {
      jQuery('.open').not(x).next().slideUp();
      jQuery('.open').not(x).removeClass('open');
      jQuery(x).addClass('open');
      jQuery(x).next().slideDown();
    }

  }
  jQuery('.answer').hide();
  jQuery('.question').click(function () {
    open_close_sections(this)
  });
});
rrk
  • 15,677
  • 4
  • 29
  • 45
Tân
  • 1
  • 15
  • 56
  • 102
  • Thanks a lot people - especially Rejith. That works brilliantly. Now I'm off to sit quietly with some jQuery tutorials and try to up my game. thanks again,] – amort2000 Jan 12 '16 at 08:09