How to toggle content in Semantic UI buttons?

20,175

Solution 1

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)
;

Solution 2

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.

Solution 3

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');
});

Solution 4

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>
Share:
20,175
Huey
Author by

Huey

Updated on April 21, 2020

Comments

  • Huey
    Huey about 4 years

    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?