0

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.

Enlico
  • 23,259
  • 6
  • 48
  • 102
Javier Muñoz
  • 732
  • 1
  • 11
  • 30

3 Answers3

3

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);
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

Your a element is not part of the DOM (Document Object Model) yet, hence a.click() will not "do" much. Within your doExportMap() function, just after the a.click(); bit, try the following:

document.getElementById("exportMapForm").appendChild(a);

Now it is part of the DOM, and will work as expected. It is in your "exportMapForm" for now, but you can append it anywhere you like ;)

1

Dud,

all you need is to execute in js this

document.location = 'http://mail.rsgc.on.ca/~ldevir/ICS3U/Chapter4/Images/tux.png'
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55