Question

The documentation says a button can be formatted to toggle on or off, but the example given is merely

<div class="ui toggle button">
    Vote
</div>

which naturally, doesn't work. An inspection of the source code of the example reveals an active class is programmatically added.

I'm probably missing something simple, but how can I create a toggle button like in that example? What's the syntax for specifying what to toggle between?

Was it helpful?

Solution

The below code is doing the magic:

semantic.button = {};

// ready event
semantic.button.ready = function() {

  // selector cache
  var
    $buttons = $('.ui.buttons .button'),
    $toggle  = $('.main .ui.toggle.button'),
    $button  = $('.ui.button').not($buttons).not($toggle),
    // alias
    handler = {

      activate: function() {
        $(this)
          .addClass('active')
          .siblings()
          .removeClass('active')
        ;
      }

    }
  ;

  $buttons
    .on('click', handler.activate)
  ;


  $toggle
    .state({
      text: {
        inactive : 'Vote',
        active   : 'Voted'
      }
    })
  ;

};


// attach ready event
$(document)
  .ready(semantic.button.ready)
;

OTHER TIPS

The easiest way to get the toggle buttons working without any options etc is the following:

$('.ui.button.toggle').state();

This should toggle between the default grey and green colors on click. See the other answers for more complicated behaviour. Make sure the DOM etc is loaded first as with other semantic UI initializers.

It is very simple,

<button class="ui toggle button active" id="tgl">Toogle button</button>

just use the classic jquery click to toogle the active class, and add any other changes you need. I think that using semantic stage is a waste of time in this case.

$('#tgl').click(function(){      
            $(this).toggleClass('active');
});

The following simple code is working fine for two different toggle buttons with onClick event. Thank you Mukesh for inspiring me.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../../dist/semantic.css">
<script src="../assets/library/jquery.min.js"></script>
<script src="../../dist/semantic.js"></script>

</head>
<script>

function show(b){
alert( $(b).hasClass("active"));
}

// attach ready event
$(document)
  .ready(function() {
  var $toggle  = $('.ui.toggle.button');
  $toggle
    .state({
      text: {
        inactive : 'Vote',
        active   : 'Voted'
      }
    })
  ;

})
;
</script>
<body>

<button class="ui toggle button" onclick="show(this)">
  Vote
</button>
<br/><br/>
<button class="ui toggle button" onclick="show(this)">
  Vote
</button>


</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top