Search code examples
javascriptjqueryhtmlopenlayersopenlayers-3

How to create <a download> without click?


I have the following jQuery and HTML code and It works perfectly:

<a id="bmpFormat">.BMP</a>

<script>
    var exportBMPElement = document.getElementById('bmpFormat');

    exportBMPElement.addEventListener('click', function(e) {
      map.once('postcompose', function(event) {
        var canvas = event.context.canvas;
        exportBMPElement.download = 'mapa.bmp'
        exportBMPElement.href = canvas.toDataURL('image/bmp');
      });
    }
</script>

But now, I'd like to call all this without to do "click", just calling a function. I've tried to do it but without succesful... I want to do it this way because I need to call this code after to validate a form. By the way, my form is within a modal div.

In fact, I've tried to do this simple example but It doesn't work:

<div class="modal>  
  <form id="exportMapForm" action="javascript:doExportMap()" role="form">
  </form>
</div>

function doExportMap() {
    var a = document.createElement('a');
    a.download = 'tux.png';
    a.href = 'http://mail.rsgc.on.ca/~ldevir/ICS3U/Chapter4/Images/tux.png';
    a.click();
}

I understand that I need to create an new element here to get the goal.


Solution

  • Appending the anchor to the DOM seems to work:

    function doExportMap() {
        var a = document.createElement('a');
        a.download = 'tux.png';
        a.href = 'http://mail.rsgc.on.ca/~ldevir/ICS3U/Chapter4/Images/tux.png';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }