• 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...

Jaxel

Well-known member
#1
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?
 

Kier

XenForo Developer
Staff member
#2
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);