Frank Mehlhop
Frank Mehlhop

Reputation: 2222

How to implement a switch control and change content by switch event

I have a html site using also bootstrap 4.4.1. The user should get a switch GUI control like that:

enter image description here

By using the control the content on the site should change by Javascript. The site should not be reloaded, so no PHP.

There are many different texts where there should be alternative content depend on the one switch.

  1. Which switch GUI element is easy to implement and use?

  2. How looks the Javascript code like for the switch function and showing / hiding the texts?

I'm happy with links to tutorials where I get this informations.

Upvotes: 0

Views: 1417

Answers (1)

Jakub Muda
Jakub Muda

Reputation: 6734

You can use Bootstrap default switch: https://getbootstrap.com/docs/4.5/components/forms/#switches

Javascript uses eventListener and on change it checks if <input type="checkbox"> is checked or not.

var id_switch = document.getElementById('switch');

id_switch.addEventListener('change',function(){
  if(this.checked == true){
    console.log('CHECKED');
  }else{
    console.log('NOT CHECKED');
  }
});
/*DEMO*/body{padding:3rem}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="custom-control custom-switch">
  <input id="switch" class="custom-control-input" type="checkbox">
  <label class="custom-control-label" for="switch">Toggle this switch element</label>
</div>

Upvotes: 2

Related Questions