Search code examples
javascriptjqueryhtmlbxslider

bxslider with dynamic html


I am using bxslider in a modal and since the modal should present images depending on the user selection, I am writing the html within the slider dynamically.

Here is my modal code:

<div class="modal fade" id="figure_carousel" role="dialog">
    <div class="modal-dialog" style="width: 80%; height: 100%;">
        <div class="modal-content">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <br>
            </div>

            <div class="modal-body">

                <ul class="bxslider" id="elements">



                </ul>

            </div>

            <div class="modal-footer">
                <input class="btn btn-default" type="button" data-dismiss="modal" value="Close" />
            </div>  

        </div>
    </div>
</div>

when an image is clicked I run the following script

<script>
    $(document).on("click",".paper_img",function(event){
        var modalview = get_html()
        document.getElementById('elements').innerHTML = ""
        $('#figure_carousel').modal('show');
        $('.bxslider').append(modalview.innerHTML);

        var slider = $('.bxslider').bxSlider({mode: 'horizontal'});
        slider.reloadSlider();
    });
</script>   

which gets some html (using the get_html function), writes it in the id=elements ul in the modal and launches the modal. Lets assume the html code which comes back from the get_html function looks like this

<li><img src="/static/sourcefiles/image.png" alt="figure"/></li>

When the modal is opened, the size of the images is wrong. If I resize the browser window manually, the slides become correct. Somehow bxslider cannot deal with me writing html code dynamically. How can I load the bxslider after writing the html code or any other way to solve this? thanks carl EDIT: Here is my problem in an example

http://plnkr.co/edit/sHVq6cggMfVVS4QywQNs?p=preview


Solution

  • your are calling the bxSlider() when the bootstrap modal is hidden. May be the reason bxSlider couldn't detect the height of the images.

    var bx;
    $('#myModal1').on('shown.bs.modal', function () {
      if(bx === undefined){
        bx= $('.bxslider').bxSlider();
      } else {
        bx.reloadSlider(); 
      }
    });
    

    'shown.bs.modal' it the bootstrap event fires when the model is made visible to user. then we call the bxSlider(), and everytime we add images we are calling bx.reloadSlider();

    example : http://plnkr.co/edit/LTMCuDUc3vUm9VnmmvzG?p=preview