Home > other >  Toggele dropdown menu with icons in bootstrap
Toggele dropdown menu with icons in bootstrap

Time:11-27

I want to toggle Pause and Enable dropdown options, when clicked it would change the icon and rename Pause to Enable and enable to pause when again clicked.

enter image description here

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material Symbols Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  </head>
  <body>
    <h1>Click more options icon</h1>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>
    
<div >
        <div >
            <button type="button"  data-bs-toggle="dropdown" aria-expanded="false">more_horiz</button>
            <ul  style="">
                <li><a  href="#"><span >pause</span> Pause</a></li>
                <li><a  href="#"><span >share</span> Share</a></li>
                <li><a  href="#"><span >content_copy</span> Copy</a></li>
                <li><a  href="#"><span >delete</span> Delete</a></li>
            </ul>
        </div>
</div>
<script>

$(".menu-switch").on("click",function(event){

if($(this).hasClass("pause"))
{
alert(true)
    $(this).parent().html(`<a  href="#"><span >play_arrow</span> Enable</a>`)
}
else
{
alert(false)
    $(this).parent().html(`<a  href="#"><span >pause</span> Pause</a>`)
}
    
})
</script>
  </body>
</html>

CodePudding user response:

You could include both variants and show them alternately.
This collapses/hide one inner div and shows the other. Ok, it's a bit of a hack but it works without js.

     <li>
        <a  data-bs-toggle="collapse" href="#idPause" aria-expanded="true">
            <div  id="idPause">
                <span >pause</span> Pause
            </div>
            <div >
                <span >play_arrow</span> Enabled
            </div>
        </a>
    </li>

The necessary css

    .text-toggle[aria-expanded=false] .text-expanded {
        display: none;
    }

    .text-toggle[aria-expanded=true] .text-collapsed {
        display: none;
    }

The CSS just toggles the paused/enabled visibility.
The JS still works the same way.

    $(".menu-switch").on("click",function(event){
        if($(this).hasClass("pause"))
        {
            alert(true);
        }
        else
        {
            alert(false);
        }
    })
  • Related