-3

I was looking for a way to write to a file in javascript.I found excatly what I was looking for here

but the problem is that it uses jquery.I am suppose to do this task with pure javascript.

My question is how would I convert a $ sign to a pure javascript without including the jquery script in the code.

In short how would I convert this code to pure javascript if its possible.

  function createDownloadLink(anchorSelector, str, fileName){
    if(window.navigator.msSaveOrOpenBlob) {
        var fileData = [str];
        blobObject = new Blob(fileData);
        $(anchorSelector).click(function(){
            window.navigator.msSaveOrOpenBlob(blobObject, fileName);
        });
    } else {
        var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
        $(anchorSelector).attr("download", fileName);   //when I try document,getElementById it does not work.            
        $(anchorSelector).attr("href", url);
    }
}

$(function () {
    var str = "kgopelo is my name in the place";
    createDownloadLink("#export",str,"file.txt");
});

Thanks in advanced.

Community
  • 1
  • 1
  • It's not the dollar you want to convert to pure JavaScript - that's the jQuery function to access all of its features. What you want to convert is the `attr`. And to do that, you can [do this search](https://duckduckgo.com/?q=set+attributes+in+plain+javascript). The first result seems to answer the question `:-)`. – halfer Apr 22 '14 at 08:46
  • Obviously, jQuery isn't just a 'sign' – jQuery performs all sorts of useful functions, and it's used for several different features in the code above. Can you work out what they are, and have you tried looking for alternatives to those features? Of course it's possible to do everything jQuery does with pure Javascript, since jQuery *is* Javascript – but you'll need to put a bit of analysis, research and effort into it. – Barney Apr 22 '14 at 08:47
  • *"when I try document,getElementById it does not work"*. I assume you mean `document.getElementById`. And if you just pass `anchorSelector` to it, it won't work indeed, because it would run `document.getElementById('#export')` instead of `document.getElementById('export')`. Then of course you also have to convert `attr` to `setAttribute`, or better, just directly assign to the DOM properties. – Felix Kling Apr 22 '14 at 08:53

1 Answers1

1

You need to replace jquery functions with plain javascript.

  1. $(anchorSelector) -> it may be replaced by getElementById or getElementByClassName
  2. .click -> How do you catch a click event with plain Javascript?
  3. attr -> I want to use javascript to insert an attribute to an element
  4. $(function(){ -> run function when page is loaded
Community
  • 1
  • 1
Machet
  • 1,090
  • 8
  • 17