Search code examples
jquerytwitter-bootstrapbootstrap-material-design

Material design wave effect not applied to dynamically created button


I am trying to create buttons by using jQuery's append method. However the buttons which where created by jQuery don't have the wave effect if I click on them. The button that I created in HTML has the wave effect.

Why is it different? How can I get the wave effect to also appear for the button which is created by jQuery?

Thanks for your help!

$('#line').append('<button type="button" class="btn btn-lg btn-primary">Button created by js</button>');
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.7.5/css/mdb.min.css" rel="stylesheet"/>

<button id="btn1" type="button" class="btn btn-lg btn-primary">
  Button
</button>

<hr id="line">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.7.5/js/mdb.min.js"></script>


Solution

  • The Waves effect from the MDBootstrap library is not automatically applied to dynamically created elements. You need to instantiate it manually on the new button. As per the documentation you can achieve that in your case by calling Waves.attach('.btn', ['waves-light']);.

    Also note that, as @VVV stated in the comments, <hr> is primarily used to define a thematic break in an HTML page, using after() instead of append() would be better as this code will not validate through W3C.

    $('#line').after('<button type="button" class="btn btn-lg btn-primary">Button created by js</button>');
    
    Waves.attach('.btn', ['waves-light'])
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.7.5/css/mdb.min.css" rel="stylesheet"/>
    
    <button id="btn1" type="button" class="btn btn-lg btn-primary">
      Button
    </button>
    
    <hr id="line">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.7.5/js/mdb.min.js"></script>