1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Generating a new spoiler tag... problems with multiple tags...

Discussion in 'XenForo Development Discussions' started by Jaxel, May 25, 2011.

  1. Jaxel

    Jaxel Well-Known Member

    I am using the following JS:
    Code:
    /** @param {jQuery} $ jQuery Object */
    !function($, window, document, _undefined)
    {
        XenForo.Spoiler = function($spoiler)
        {
            $content = $spoiler.find('.spoilerContent');
            $toggle = $spoiler.find('.spoilerToggle');
            $content.hide();
    
            $toggle.click(function(e)
            {
                e.preventDefault();
                $content.toggle('slow');
            });
        }
    
        // *********************************************************************
    
        XenForo.register('.bbCodeSpoiler', 'XenForo.Spoiler');
    }
    (jQuery, this, document);
    You can see it here:
    http://www.8wayrun.com/threads/8wayrun-com-now-running-the-xenforo-beta.6406/page-10#post-237171

    The problem, which you can easily see, is that no matter which toggle button, it always toggles the last spoiler block. Why is this? I thought the $spoiler.find function would only find child classes, not all of them. How do I get around this?
     
  2. Kier

    Kier XenForo Developer Staff Member

    It's because $content and $toggle are effectively global variables. To limit them to the scope of the containing function, you must use var.

    Code:
    /** @param {jQuery} $ jQuery Object */
    !function($, window, document, _undefined)
    {
        XenForo.Spoiler = function($spoiler)
        {
            var $content = $spoiler.find('.spoilerContent').hide(),
    
            $toggle = $spoiler.find('.spoilerToggle').click(function(e)
            {
                e.preventDefault();
                $content.toggle('slow');
            });
        }
    
        // *********************************************************************
    
        XenForo.register('.bbCodeSpoiler', 'XenForo.Spoiler');
    }
    (jQuery, this, document);
     
  3. Jaxel

    Jaxel Well-Known Member

    Thanks, I didn't realise thats what var did.
     

Share This Page