Last Updated: February 25, 2016
·
1.051K
· rayfranco

jQuery class toggler

This is a small snippet written in coffeescript that became useful to me and my team in several projects and many situations.

Its only mission is to toggle classes.

You're saying that jQuery do this already, I can hear you ! Well, I know, actually this is just a wrapper to let the DOM deal with it in a straightforward way.

Look at this :

<a class="toggler" href="#" data-target="#target">Toggle the target</a>
<div id="target">I am the target</div>

Then implement the plugin, the way you want :

$('.toggler').classToggler()

You could also pass parameters and callback methods :

$('.toggler').classToggler
    onToggle: (el, target, active) ->
        if active 
            el.text 'Set target to inactive' 
            target.text 'I am the target, and I am active'
        else
            el.text 'Set target to active'
            target.text 'I am the target, and I am inactive'

Look at this example on jsFiddle

Here is the snippet :

$ = jQuery

defaults =
    target: null
    preventDefault: true
    className: 'active'
    onClick: null
    onToggle: null

class Toggler
    constructor: (@el, settings) ->
        @settings = $.extend {}, defaults, settings
        target = @el.data('target')
        if target
            @target = $(target)
        else if @settings.target
            @target = $(@settings.target)
        else
            @target = @el
        @el.on 'click', (e) =>
           e.preventDefault() if @settings.preventDefault
           @settings.onClick?(e,@el)
           @toggle()
    toggle: (active) ->
        @target.toggleClass @settings.className, active
        @settings.onToggle?(@el, @target, @target.hasClass(@settings.className))

(($) ->
  $.fn.classToggler = (settings) ->
    new Toggler(@, settings)
)(jQuery)

Quite straight to the point...